Static Nested Classes

Restriction on Static Nested Classes

static keyword can be applied on classes and interfaces only when they are nested. Top-level classes and interfaces cannot be static.

This is the second variation of the total six discussed in this series.

Note: It is advised to read the basics and types of inner classes before proceeding further.

Let go on this combination – Static Nested Classes
public class Outer1              
  int x = 10;
  static int y = 20;	

  static class Inner1	
    int k = 30;    
    static int m = 40; 
    public void display()
      // System.out.println(x);                // raises compilation error

  public static void main(String args[])
    Outer1.Inner1 i1 = new Outer1.Inner1();    // 1st style of creating static inner class object

    Inner1 i2 = new Outer1.Inner1();           // 2nd style of creating static inner class object  

The slight modification in this program than the previous Java Nested Classes is here the inner class is declared static. The inner class can have static and non-static members like the outer class. But the restriction is "the static inner class cannot access outer class non-static members". For this reason, printing of x variable in display() method is commented out. It can directly call outer class static member, y.

One more difference we can observe is creating object of static inner class. We know in OOPs, a static member call be called with a class name also.

Ealier: Non-static inner class object creation: Outer1.Inner1 i2 = new Outer1().new Inner1();

Now with static inner class: Outer1.Inner1 i1 = new Outer1.Inner1();

In the above statement, Outer1 constructor is not necessary. Just class name is enough.

Because inner classes usage is growing slowly, they are discussed more elaborately here. Android (Java based Mobile OS developed by Google) uses inner classes very extensively, infact anonymous inner classes are passed as parameters to methods.

3 thoughts on “Static Nested Classes”

Leave a Comment

Your email address will not be published.