A static nested class is an inner class marked with static modifier.
A static nested class is sometimes called as static inner class. A static nested class does not have a relationship with the outer class as it can not access instance non static members of the outer class. This is because the nested class instance does not have this reference to the outer class.
Due to the above mentioned reasons, a static nested class is a top-level nested class and is not an inner class.
class Outer {
static int x = 10;
static class Inner {
public void print() {
System.out.println("Access x in outer: " + x);
}
}
}
Instantiating static nested class and its usage
A static nested class is a static member of outer class. It can be accessed without having an instance of the outer class. This is same as other static members of the class.
The syntax to create instance of static nested class is:
Outer.Inner inner = new Outer.Inner();
Here, Outer is the outer class and Inner is the static nested class in Outer.
Let us see this with an example.
package com.learnitweb;
class Outer {
static int x = 10;
static class Inner {
public void print() {
System.out.println("Access x in outer: " + x);
}
}
}
public class Test {
public static void main(String args[]) {
Outer.Inner inner = new Outer.Inner();
inner.print();
}
}
Output
Access x in outer: 10
Explanation
Outeris a class. This class hasstaticvariable x. This class also has static nested classInner.Innerclass has a methodprint(). This method accessstaticOuter class variable x and prints.Testis a class withmainmethod.mainmethod creates instance ofInnerclass. Notice the syntaxOuter.Inner inner = new Outer.Inner();.Inneris a static member ofOuterand can be accessed without having instance ofOuter.printmethod is called on instance ofInnerwhich prints the variable x.
Summary
- A static nested class is an inner class marked with static modifier.
- A static nested class can only access static members of outer class. A static nested class can not access non static member variable or methods.
- The syntax to instantiate the static nested class is : Outer.Inner inner = new Outer.Inner();
- The static nested class does not have the special relationship with the outer class.
- Static nested class is a top-level nested class and is not an inner class.
