Static nested classes

Static nested classes
  • Sometimes we can declare inner classes with static modifier such type of inner classes are called static nested classes.
  • In the case of normal or regular inner classes without existing outer class object there is no chance of existing inner class object. i.e., inner class object is always strongly associated with outer class object.
  • But in the case of static nested class without existing outer class object there may be a chance of existing static nested class object. i.e., static nested class object is not strongly associated with outer class object.
package com.ashok.innerclasses;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class MyStaticInner {
   static class NestedClass {
      public void methodOne() {
         System.out.println("Welcome to Waytoeasylearn");
      }
   }

   public static void main(String[] args) {
      MyStaticInner.NestedClass nestedClass = new MyStaticInner.NestedClass();
      nestedClass.methodOne();
   }
}

Output

Welcome to Waytoeasylearn

Inside static nested classes we can declare static members including main() method also. Hence it is possible to invoke static nested class directly from the command prompt.

package com.ashok.innerclasses;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class MyStaticInner {
   static class NestedClass {
      public static void main(String[] args) {
         System.out.println("Inside Inner class main method");
      }
   }

   public static void main(String[] args) {
      System.out.println("Inside Outter class main method");
   }
}

Output

D:\Ashok\Java>javac MyStaticInner.java
D:\Ashok\Java>java MyStaticInner
Inside Outter class main method
D:\Ashok\Java>java MyStaticInner$NestedClass
Inside Inner class main method

Note

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.

Capture 28
Static nested classes

Scroll to top