What is an Inner class in Java?

Java 8Object Oriented ProgrammingProgramming

A nested class in Java is of two types i.e. Static nested class and Inner class. An inner class is a non-static nested class. Inner class is a security mechanism in Java as it can be private while normal classes cannot.

A program that demonstrates an inner class is given as follows:

Example

 Live Demo

public class Class1 {
   private int a = 7;
   class Class2 {
      void func() {
         System.out.println("This is an inner class");
         System.out.println("a = " + a);
      }
   }
   public static void main(String args[]) {
      Class1 obj1 = new Class1();
      Class1.Class2 obj2 = obj1.new Class2();
      obj2.func();
   }
}

Output

This is an inner class
a = 7

Now let us understand the above program.

The class Class1 is the outer class and the class Class2 is the inner class. The method func() in Class2 prints "This is an inner class class" and the value of a that is declared in Class1. A code snippet which demonstrates this is as follows:

public class Class1 {
   private int a = 7;
   class Class2 {
      void func() {
      System.out.println("This is an inner class");
      System.out.println("a = " + a);
   }
}

An object obj1 of the outer class(Class1) and obj2 of the inner class(Class2) is declared in the method main() in Class1. Then func() is called. A code snippet which demonstrates this is as follows:

public static void main(String args[]) {
   Class1 obj1 = new Class1();
   Class1.Class2 obj2 = obj1.new Class2();
   obj2.func();
}
raja
Published on 15-Feb-2019 11:00:54
Advertisements