What is a static class in Java?

Java 8Object Oriented ProgrammingProgramming

You cannot use the static keyword with a class unless it is an inner class. A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class.

Syntax

class MyOuter {
   static class Nested_Demo {
   }
}

Instantiating a static nested class is a bit different from instantiating an inner class. The following program shows how to use a static nested class.

Example

Live Demo

public class Outer {
   Java Arrays with Answers
   static class Nested_Demo {
      public void my_method() {
         System.out.println("This is my nested class");
      }
   }
   public static void main(String args[]) {
      Outer.Nested_Demo nested = new Outer.Nested_Demo();
      nested.my_method();
   }
}

Output

If you compile and execute the above program, you will get the following result −

This is my nested class
raja
Published on 09-Feb-2018 11:26:45
Advertisements