Java static nested class



Static Nested Class in Java : Nested Class

Consider the following example of the static nested class

package com.c4learn.nestedclss;

class OuterClass {
    private static int serialNo = 10;

    static class InnerClass {
	int getValue() {
	   return serialNo;
	}
    }
}

public class StaticNestedClassExample {

   public static void main(String[] args) {
     OuterClass.InnerClass m1 = new OuterClass.InnerClass();
     System.out.println("Sr. Number :" + m1.getValue());
   }
}

Explanation :

  1. We can refer the nested class using the following syntax –
OuterClassName.InnerClassName
  1. You have access to the outer class static members from inside your static nested class. Consider the following Static Nested Class –
class OuterClass {
   private static int serialNo = 10;
   private int panNo  = 10;
   public  int rollNo = 20;
	
   static class InnerClass {
     int getValue() {
	return serialNo;
     }
   }
}
Variable NameMethod of InnerClass can return VariableExplanation
serialNoYesVariable is static so we can return
panNoNoVariable is Non Static
rollNoNoVariable is Non Static
  1. No need to create an instance of the enclosing class to instantiate a static nested class.
OuterClass outObj = new OuterClass();

There is no need to create instance of the Outer Class in order to access Inner Static Class

What would happen if Same Variable is declared inside Inner Class ?

If you declare a member in a nested class that has the same name as a member in the Outer class then Inner member will shadow Outer Class member –

package com.c4learn.nestedclss;

class OuterClass {
   private static int serialNo = 10;

   static class InnerClass {
      int serialNo = 20;
      int getValue() {
	 return serialNo;
      }
   }
}

public class StaticNestedClassExample {

   public static void main(String[] args) {
      OuterClass.InnerClass m1 = new OuterClass.InnerClass();
      System.out.println("Sr. Number :" + m1.getValue());
   }
}

Output :

Sr. Number : 20