Static nested classes

Static nested classes

In this tutorial, we are going to discuss about the Static nested classes. Static nested classes in Java are nested classes that are declared with the static keyword. Unlike regular inner classes, static nested classes do not have access to the instance variables and methods of the outer class.

They are essentially independent from instances of the outer class, allowing them to be instantiated without an instance of the outer class.

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

That’s all about the Static nested classes in java. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!!

Static nested classes
Scroll to top