- Non-Static Nested Class. (Also called as Inner Class)
- Static Nested Class.
- Local Class (Nested Class inside a code block)
- Anonymous Nested Class.
private members. However the Enclosing Class does not have access to the data Member's of Nested Class directly.
Non-Static Nested Class
A Non-Static Nested Class or a Inner Class id defined without thestatic keyword and has access to all the member's of the Outer Class, and can refer to them Directly without creating the Object of Outer Class. Let's consider this example.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an Inner Class
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
}
class InnerClassDemo {
public static void main(String args[]){
Outer outer = new Outer();
outer.test();
}
}
Output:
display: outer_x = 100
Static Nested Class
A static Nested Class only have access to thestatic data members of the enclosing Class. It cannot access non-static members of Outer Class.
Local Class
Local classes in Java are like inner classes that are defined inside a method or scope block ({ ... }) inside a method. Here is an example:class Outer {
public void testMethod(){
class LocalClass{
int x = 10;
public void display(){
System.out.println("This is a local class")
}
}
}
}
Local classes can only be accessed from inside the method or scope block in which they are defined.
Local classes can access members (fields and methods) of its enclosing class just like regular inner classes.