3.2) Inner class (also called member class)
Last updated
Last updated
The definition of an inner class is enclosed within another class, also referred to as an outer class. An inner class is an instance member of its outer class. An instance of an inner class shares a special bond with its outer class and can’t exist without its instance
You’d usually create an inner class to encapsulate partial functionality of your main class such that the existence of the inner class instance isn’t possible without its outer class instance. This is in contrast to a nested static class, which can be used without an instance of its outer class.
For example, the following code defines a class Tree and an inner class TreeSort. Tree defines operations to add, remove, and sort objects based on a condition. Instead of defining methods and variables to sort the tree elements within class Tree, it encapsulates sorting functionality within class TreeSort. Class TreeSort would always work with Tree and might not be needed without class Tree:
Because an inner class is a member of its outer class, an inner class can be defined using any of the four access levels: public, protected, default access, and private. Like a regular top-level class, an inner class can also define constructors, variables, and methods. But an inner class can’t define nonfinal static variables or methods, as shown in figure
Whenever you instantiate an inner class, remember that an instance of an inner class can’t exist without an instance of the outer class in which it’s defined. Let’s look at cre- ating an inner class:
Within an outer class, as an instance member
Within a method of an outer class
Within a static method of an outer class
Outside the outer class
You must have an outer class instance to create an inner class instance.
The accessibility of an inner class outside its outer class depends on the access modifier used to define the inner class. For example, an inner class with default access can’t be accessed by classes in different packages than the outer class.
An inner class is a part of its outer class. Therefore an inner class can access all vari- ables and methods of an outer class, including its private members and the ones that it inherits from its base classes. An inner class can also define members with the same name as its outer class, as shown in figure
An object uses the reference this to refer to its own object. An inner class can use the reference this to refer to its own object, and the name of its outer class followed by .this to refer to the object of its outer class, as shown in figure.
Yes, an inner class can exist only with an object of its outer class. When a compiler compiles an inner class, it seems to insert code in the inner class, which defines an instance variable of its outer class, initialized using its constructor, as illustrated in figure :