Inner Classes
- Inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields.
- It’s allowed only final variable.
- Also, because an inner class is associated with an instance, it cannot define any static members itself.
- Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:
class OuterClass {
...
class InnerClass {
...
}
}
- To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass()
Local Inner Classes
- We can declare an inner class within the body of a method. Such a class is known as a local inner class.
- A local class is a nested class that is not a member of any class and that has a name.
- Every local class declaration statement is contained by a block.
- Local class defined in a method has access to final method variables and also to the outer class's member variables.
Anonymous Inner Classes
- We can declare an inner class within the body of a method without naming its called anonymous inner classes.
- An anonymous class is an inner class with the usual
- class body, but
- No class name
- No access specifier (i.e., no public/private/protected)
- No constructor
- No explicit use of extends or implements
- It either extends one class or implements one interface
- An anonymous class is never abstract. An anonymous class is always an inner class; it is never static. An anonymous class is always implicitly final.
- Are commonly used in Swing code to implement listeners or adapters.
Syntax for Anonymous Classes
new class-name ( [ argument-list ] ) { class-body }
or:
new interface-name () { class-body }
When to Use an Anonymous Class
- The class has a very short body.
- Only one instance of the class is needed.
- The class is used right after it is defined.
- The name of the class does not make your code any easier to understand.