1. Nested Classes in Java
A nested class is any class defined inside another class. Java allows classes to be nested for better organization, encapsulation, and readability.
There are two main types:
A. Static Nested Class
- Declared
static
inside another class. - Can access only static members of the outer class directly.
- Does not have a reference to the outer class instance.
- Can be instantiated without an instance of the outer class.
Example:
class Outer {
static int outerStatic = 10;
static class Nested {
void display() {
System.out.println("Static Nested class: " + outerStatic);
}
}
}
public class Test {
public static void main(String[] args) {
Outer.Nested nested = new Outer.Nested();
nested.display();
}
}
Output:
Static Nested class: 10
B. Inner Classes (Non-Static Nested Class)
- Declared without
static
inside another class. - Can access all members (including private) of the outer class.
- Has an implicit reference to the outer class instance.
- Cannot have static members (except final constants).
- Needs an instance of the outer class to be created.
Example:
class Outer {
private int outerVar = 5;
class Inner {
void display() {
System.out.println("Inner class: " + outerVar);
}
}
}
public class Test {
public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner(); // note: outer.new Inner()
inner.display();
}
}
Output:
Inner class: 5
2. Other Types of Inner Classes
Java also supports special forms of inner classes:
- Local Inner Class
- Defined inside a method.Can access final or effectively final variables of the method.
class Outer {
void show() {
int num = 10;
class LocalInner {
void display() {
System.out.println("Local inner class: " + num);
}
}
LocalInner li = new LocalInner();
li.display();
}
}
- Anonymous Inner Class
- Defined without a class name.Typically used for interfaces or abstract classes on-the-fly.
abstract class Person {
abstract void greet();
}
public class Test {
public static void main(String[] args) {
Person p = new Person() {
void greet() {
System.out.println("Hello from anonymous class!");
}
};
p.greet();
}
}
3. Key Differences Between Static Nested and Inner Classes
Feature | Static Nested Class | Inner Class (Non-static) |
---|---|---|
Reference to outer class | No | Yes |
Can access outer class members | Only static members | All members |
Instantiation | Outer.Nested nested = new Outer.Nested(); | Outer.Inner inner = outer.new Inner(); |
Can have static members | Yes | No |