Static Nested Classes

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

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 Reply

Your email address will not be published. Required fields are marked *