Java static nested class
Contents
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 :
- We can refer the nested class using the following syntax -
OuterClassName.InnerClassName
- 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 Name | Method of InnerClass can return Variable | Explanation |
---|---|---|
serialNo | Yes | Variable is static so we can return |
panNo | No | Variable is Non Static |
rollNo | No | Variable is Non Static |
- 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