Nested classes that are declared with static keyword is called as static nested class. It can only access the static members of the outer class.

Example:

//outer class

class OuterClass {

...

//inner class

static class StaticNestedClass {

...

}

}

  • Inside static nested classes we can declare static members including main() method also.
  • From the normal inner class we can access both static and non static members of outer class but from static nested class we can access only static members of outer class.

In the above program, we are accessing the static nested class code without creating an object for the outer class. We can also take the main() method inside the static nested class.

Inner classes vs static nested classes

 

Normal inner classes Static nested classes
1. Inside normal or regular inner class we can’t declare static members. 1. Inside static nested class we can declare static members.
2. Inside normal inner class we can’t declare main() method. 2. Inside static nested class we can declare main() method.
3. From the normal or regular inner class we can access both static and non static members of outer class directly. 3. From static nested class we can access only static members of outer class directly.