Mastering nested structures: Member, Static Nested, Local, and Anonymous classes
An Inner Class (or Nested Class) is a class declared inside another class or interface. It allows you to logically group classes that are only used in one place, enhancing encapsulation and readability.
Declared inside a class, outside methods. Needs an outer object instance to exist.
Declared with static. Independent of outer class instances.
Declared inside a method body. Scope is restricted to that method.
A class without a name declared and instantiated in a single expression.
Click through the tabs to see how each inner class type is instantiated and how it accesses outer members.
class Outer {
private String secret = "Outer Private Secret";
// Member Inner Class
class Inner {
void reveal() {
System.out.println(secret); // Directly accesses private outer field!
}
}
}
// Instantiation Syntax: Requires Outer Instance
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.reveal();
class Outer {
static String appName = "JavaApp";
// Static Nested Class
static class Nested {
void display() {
System.out.println("App Name: " + appName);
// Cannot access non-static outer members directly!
}
}
}
// Instantiation Syntax: No Outer Instance Needed!
Outer.Nested nested = new Outer.Nested();
nested.display();
class Outer {
void processData() {
int factor = 2; // Must be effectively final
// Local Class defined inside method
class Calculator {
int multiply(int val) { return val * factor; }
}
Calculator calc = new Calculator();
System.out.println("Result: " + calc.multiply(10));
}
}
interface Greeting {
void sayHello();
}
class Main {
public static void main(String[] args) {
// Anonymous Class implementing Greeting interface on the fly
Greeting g = new Greeting() {
public void sayHello() {
System.out.println("Hello from Anonymous Class!");
}
};
g.sayHello();
}
}