Object-oriented programming for Java - 8

Java Nested and Inner Class

 

 


1. Java Non-Static Nested Class (Inner Class)

1.1 Inner Class

Example:

In this example, there are two nested classes: Processor and RAM inside the outer class:CPU

(Inner Classes Create)

 

1.2 Accessing Members of Outer Class within Inner Class (Accessing Members)

In this example, code are using this keyword to access the CarType variable of the outer class.

 

2. Java Static Nested Class

In Java, we can also define a static class inside another class.

A static nested class cannot access the member variables of the outer class.

2.1 Static Inner Class

 

2.2 Accessing members of Outer class inside Static Inner Class (Accessing Members)

Error Example: (Wrong EX)