Java inner class and static nested class
In Java, an inner class is a class that is defined within another class. An inner class has access to the members (fields and methods) of the outer class, and can be used to encapsulate the implementation of a component of the outer class.
Here's an example of an inner class in Java:
public class OuterClass {
private int x;
public class InnerClass {
public void doSomething() {
// Access the field x of the outer class
System.out.println(x);
}
}
}
To create an instance of the inner class, you need to first create an instance of the outer class, and then use the new
operator to create the inner class object. For example:
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.doSomething();
A static nested class is a class that is defined within another class, but is marked with the static
keyword. A static nested class does not have access to the non-static members of the outer class, and can be used to encapsulate utility methods or constants that are related to the outer class.
Here's an example of a static nested class in Java:
public class OuterClass {
private int x;
public static