3.4) Method local inner classes

The method local inner classes are defined within static or instance methods of a class. Though these classes can also be defined within code blocks, they are typically created within methods.

Figure below shows the definition of a bare-bones method local inner class, Inner, defined within method outerMethod() of class Outer. The Java compiler generates separate class files for the classes Outer and Inner. Because a class can define method local inner classes with the same name in separate methods, the Java compiler adds a number to the name of the compiled file for the local inner classes.

For the preceding code, the Java compiler will generate three class files: Outer.class, Outer$1Inner.class, and Outer$2Inner.class.

CHARACTERISTICS OF METHOD LOCAL INNER CLASSES:

Recall that none of the variables within a method can be defined using any explicit modifier (public, protected, private). Similarly, method local inner classes can’t be defined using any explicit access modifier. But a method local inner class can define its own constructors, variables, and methods by using any of the four access levels:

CREATION OF A LOCAL INNER CLASS:

WHAT CAN A METHOD LOCAL INNER CLASS ACCESS?:

A method local inner class can access all variables and methods of its outer class, including its private members and the ones that it inherits from its base classes. A method local inner class can also define members with the same name as its outer class. In this case, the members of the outer class can be referred to by using the name of the outer class followed by the implicit reference this. Class Inner can access members of class Outer by using Outer.this, as shown in the following code:

Disadvantages of inner classes:

Using inner classes is an advanced concept, and it can be difficult for inexperienced programmers to identify, implement, and maintain them.

Last updated