Java Inner classes
javaIn Java, an inner class is a class defined within another class. Inner classes have access to all the variables and methods of the outer class and can be used to group related functionality or to implement helper classes.
There are four types of inner classes in Java:
- Non-static inner classes (also called inner classes) have an enclosing instance and can access all the variables and methods of the outer class.
- Static inner classes (also called nested classes) do not have an enclosing instance and can only access the static variables and methods of the outer class.
- Local classes are defined within a block of code and can only be used within that block. They have the same scope as local variables.
- Anonymous classes are inner classes without a name. They are often used to create objects of a specific type on the fly.
Here is an example of an inner class in Java:
public class OuterClass {
private int x = 10;
public class InnerClass {
public void printX() {
System.out.println(x);
}
}
}
To create an instance of the inner class, you must first create an instance of the outer class:
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.printX(); // prints 10
Other Article on Tag java
- - after and before in java date
- - am pm java date format
- - apk minecraft java edition
- - as been blocked by CORS policy Response to preflight request doesn't pass access control check It does not have HTTP ok status
- - bubble sort in java
- - Can I compile and run a spring boot jar from inside another spring boot application
- - convert java date to localdate
- - design patterns in java
- - encrypt by java and decrypt by node
- - exception handling in java