Why do we need inner classes in Java?



Inner classes are a security mechanism in Java. We know 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.

Following is the program to create an inner class and access it. In the given example, we make the inner class private and access the class through a method.

Example

Live Demo

class Outer_Demo {
   int num;
   // inner class
   private class Inner_Demo {
      public void print() {
         System.out.println("This is an inner class");
      }
   }
   //Accessing he inner class from the method within
   void display_Inner() {
      Inner_Demo inner = new Inner_Demo();
      inner.print();
   }
}
public class My_class {
   public static void main(String args[]) {
      //Instantiating the outer class
      Outer_Demo outer = new Outer_Demo();
      
      //Accessing the display_Inner() method.
      outer.display_Inner();
   }
}

Output

This is an inner class.

Advertisements