i

JAVA Complete Course

Nested And Inner Classes

In Java programming language we can have a class inside another class and it is called nested class. There are two types of nested classes: Non-static nested classes, also known as inner classes and static nested classes.

Non-static nested class is a class within another class, where the class has access to members of the enclosing class (outer class). It is commonly known as inner class. As inner classes are inside the outer class, in order to initialize any inner class, first we need to initialize an outer class.

Accessing Members of Outer Class within Inner Class

In Java, we also can have static nested classes. Unlike inner class, static nested class cannot access the member variables of the outer class because static nested class doesn't require you to create an instance of outer class. Hence, no reference of the outer class exists with OuterClass.this.

Accessing members of Outer class inside Static Inner Class

Differences:

Static nested classes do not directly have access to non-static variables and methods of the outer class because as it is static, it must access the non-static members of its outer class through an object. That is, it cannot refer to non-static members of its outer class directly. Because of this restriction, static nested classes are rarely used.

Non-static nested classes (inner classes) has access to all static and non-static variables and methods (including private) of its outer class and may refer to them directly in the same way that other non-static members of the outer class do.