xxxxxxxxxx
A regular nested class cannot access members of its outer class. But a nested class marked as an inner class can.
xxxxxxxxxx
In Java, it is possible to define a class within another class, such
classes are known as nested classes. They enable you to logically group
classes that are only used in one place, thus this increases the use of
encapsulation, and creates more readable and maintainable code.
xxxxxxxxxx
public class OuterClass {
// Member variable
private int outerVariable = 10;
// Inner class
public class InnerClass {
// Inner class method
public void display() {
System.out.println("Inner class method: " + outerVariable);
}
}
// Static nested class
public static class StaticNestedClass {
// Static nested class method
public void display() {
System.out.println("Static nested class method");
}
}
public static void main(String[] args) {
// Create an instance of the outer class
OuterClass outerObj = new OuterClass();
// Create an instance of the inner class
InnerClass innerObj = outerObj.new InnerClass();
// Call the inner class method
innerObj.display();
// Create an instance of the static nested class
StaticNestedClass staticNestedObj = new StaticNestedClass();
// Call the static nested class method
staticNestedObj.display();
}
}