An inner class is a class defined inside another class. It is mainly used
when a class is closely related to another class and is not useful on its
own.
Inner classes help:
Organize related code
Improve readability
Limit the scope of helper classes
Defining an Inner Class
A class can be declared inside another class just like a method.
Example: Creating a basic inner class
Accessing an Inner Class from Outside
To use an inner class, you must first create an object of the outer class,
then create an object of the inner class using that instance.
Example: Accessing and using an inner class
Accessing Outer Class Data from an Inner Class
By default, an inner class does not automatically know about the outer class
instance. To access outer class data, pass the outer object explicitly.
Example: Passing the outer class instance
Practical Use Case of Inner Classes
Inner classes are highly useful for modeling sub-components that inherently
belong to a larger object (often called object composition).
[Image showing object composition: a Laptop object containing a Battery object
component]
Example: Using an inner class to represent a laptop’s battery
Using Multiple Inner Classes
An outer class can contain more than one inner class to represent different
distinct components.