Java inner classes are classes defined within another class that are used to improve encapsulation and code organization. In this chapter, we will learn creating and using inner classes with the help of examples.
An inner class (or nested class) is a class declared inside another class or interface. Inner classes help logically group related classes in one place to make the code more readable and maintainable. They can also access all members of the outer class, including private fields and methods.
An inner class is created by defining a class inside another class. Here are the steps to create an inner class:
Here is the syntax to create an inner class:
In this example, we have an outer class Student with an inner class Address. The inner class stores the student's address and displays it along with the student's name.
Output:
Student Name: Rahul City: Delhi State: Delhi
The following are the main two advantages of using inner classes:
Nested classes are classified into two main types: non-static nested classes and static nested classes. The non-static nested classes are commonly referred to as inner classes.
Inner classes are non-static classes defined within another class. They are further categorized into:
A static nested class is a static class defined within another class. It can access only static members of the outer class directly.
An interface defined inside a class or another interface. Nested interfaces are often used to logically group related interfaces.
We request you to subscribe our newsletter for upcoming updates.