In Java, nesting classes (placing a class within another class) is permissible. Nested classes are employed to consolidate related classes, enhancing code readability and maintainability.
To access the inner class, instantiate the outer class followed by the inner class.
|
In contrast to a “regular” class, an inner class can be designated as private or protected. To restrict external access to the inner class, declare it as private:
class OuterClass { int x = 10;
private class InnerClass { int y = 5; } } public class Main { public static void main(String[] args) { OuterClass myOuter = new OuterClass(); OuterClass.InnerClass myInner = myOuter.new InnerClass(); System.out.println(myInner.y + myOuter.x); } } |
Main.java:13: error: OuterClass.InnerClass has private access in OuterClass OuterClass.InnerClass myInner = myOuter.new InnerClass(); ^ |
An inner class can also be static, allowing access without the need to instantiate an object of the outer class.
class
}
public }
|
Note: just like static attributes and methods, a static inner class does not have access to members of the outer class. |
An advantage of inner classes is their ability to access attributes and methods of the outer class:
class
}
// Outputs 10
|