Learnitweb

Static Nested Class in Java

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

  1. Outer is a class. This class has static variable x. This class also has static nested class Inner.
  2. Inner class has a method print(). This method access static Outer class variable x and prints.
  3. Test is a class with main method.
  4. main method creates instance of Inner class. Notice the syntax Outer.Inner inner = new Outer.Inner();. Inner is a static member of Outer and can be accessed without having instance of Outer.
  5. print method is called on instance of Inner which prints the variable x.

Summary

  1. A static nested class is an inner class marked with static modifier.
  2. 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.
  3. The syntax to instantiate the static nested class is : Outer.Inner inner = new Outer.Inner();
  4. The static nested class does not have the special relationship with the outer class.
  5. Static nested class is a top-level nested class and is not an inner class.