Nested class in Java

Java allows us to define a class that belongs to another class, for example:

Class is defined inside another class, we call it nested class and this other class is called outer class. In my example above, the Builder is a nested class and the Application is an outer class. A nested class is also divided into two different types: Non-static nested class and Static nested class. How is it in detail? In this tutorial, we will learn about nested classes in Java.

Non-static nested class

Non-static nested classes are also known as Inner classes. We can declare these Inner classes inside another class like the Builder class above, inside some method (Method-local Inner Class), in addition, we also have classes that are not named Anonymous Inner Class.

Other than declaring a class, we cannot declare it with the private access modifier, for the Inner class we can do this. Like the above example, I can declare class Builder as private as follows:

But once you have declared a private Inner class, it can only be accessed inside the class it is declared!

To initialize an Inner class, you need to initialize the object for the outer class first. For example:

When we declare a class inside a method, called Method-local Inner Class, the scope of this class belongs only to that method. You cannot declare this class with the access modifier in this case. For example:

And thus, we can only instantiate the object of this class inside the method:

You can declare the final class or abstract class inside a method.

Or:

Anonymous Inner Class is often declared when we want to override a certain method of a class or interface. We will declare Anonymous Inner Class and instantiate the object for this class at the same time. For example:

You can also declare Anonymous Inner Class outside the method as follows:

Static Nested Class

It is a static member of the outer class and therefore we do not need to initialize the object of the outer class and this class itself to access it. For example:

The static nested class will not have access to fields, methods which are non-static of the outer class. Eg:

Nested class in Java

We cannot declare a static nested class inside the method!

Add Comment