What is a Nested Class in Java?

Java 8Object Oriented ProgrammingProgramming

A nested class is a class inside a class in Java. It is of two types i.e. Static nested class and Inner class. A static nested class is a nested class that is declared as static. An inner class is a non-static nested class.

A program that demonstrates a static nested class is given as follows:

Example

 Live Demo

public class Class1 {
   static class Class2 {
      public void func() {
         System.out.println("This is a static nested class");
      }
   }
   public static void main(String args[]) {
      Class1.Class2 obj = new Class1.Class2();
      obj.func();
   }
}

Output

This is a static nested class

Now let us understand the above program.

The class Class1 is the outer class and the class Class2 is the static nested class. The method func() in Class2 prints "This is a static nested class". A code snippet which demonstrates this is as follows:

public class Class1 {
   static class Class2 {
      public void func() {
         System.out.println("This is a static nested class");
      }
   }
}

An object obj 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.Class2 obj = new Class1.Class2();
   obj.func();
}
raja
Published on 19-Feb-2019 10:32:28
Advertisements