Static Nested Classes in Java

Java 8Object Oriented ProgrammingProgramming

A nested class in Java 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. A nested nested class cannot access the data members and methods of the outer 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 15-Feb-2019 06:34:05
Advertisements