Inner Class
Inner Class
There are
basically four types of inner classes in java.
Inner Classes (Non-static Nested Classes) - Inner classes are a security mechanism in Java.
Since, a class cannot be associated with the access modifier private, but if we have the class as a
member of other class, then the inner class can be made private. And this is also used to access the
private members of a class.
There are 3 types of Non-Static Nested Classes based on where we declare them -
1. Inner Class -
➢ We just need to write a class within a class.
➢ Unlike a class, an inner class can be private and once you declare an inner class private, it
cannot be accessed from an object outside the class.
class Outer_Demo { // Private Inner Class (Example 1)
int num;
private class Inner_Demo { // inner class
public void print() {
System.out.println("This is an inner class");
}
}
void display_Inner() { // Accessing he inner class from the method within
Inner_Demo inner = new Inner_Demo();
inner.print();
}
}
public class My_class {
public static void main(String args[]) {
Outer_Demo outer = new Outer_Demo(); // Instantiating the outer class
outer.display_Inner(); // Accessing the display_Inner() method.
}
}
Output:
This is an inner class.
Example 2:
class Outer { // Public / Default Inner Class Example
class Inner { // Simple nested inner class
public void show() {
System.out.println("In a nested class method");
}
}
}
class Main {
public static void main(String[] args) {
Outer.Inner in = new Outer().new Inner();
in.show();
}
}
Output:
In a nested class method
➢ Method local inner class can’t be marked as private, protected, static and transient but can be
marked as abstract and final, but not both at the same time.