Java allows defining classes within other classes or methods, known as inner classes. These include member, local, anonymous, and static inner classes.
Member Inner Classes
A member inner class is defined with in another class and has access to all members of the outer class, including private and static members.
class Shape {
private double size = 0;
public Shape(double size) {
this.size = size;
}
class Renderer {
public void display() {
System.out.println(size);
}
}
}
To access outer class members when names conflict:
OuterClass.this.member
Creating an instance requires an outer class instance:
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
Local Inner Classes
Defined within a method or scope, accessible only within that context:
class Person {
public Person getEmployee() {
class Employee extends Person {
int id = 0;
}
return new Employee();
}
}
Cannot use public, protected, private, or static modifiers.
Anonymous Inner Classes
Commonly used for event listeners, implementing interfaces without explicit class definition:
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Implementation
}
});
Static Inner Classes
Independent of outer class instances, cannot access non-static outer members:
class Container {
static class Box {
public Box() {}
}
}
// Instantiation
Container.Box box = new Container.Box();
Key Points
- Member inner classes maintain a reference to the outer class
- Local and anonymous classes can only access final local variables
- Static inner classes don't hold outer class references
- Inner classes enable better encapsulation and multipel inheritance simulation