Trong Java, có thể định nghĩa một lớp bên trong lớp khác, gọi là Nested Classes (lớp lồng). Có thể dùng access modifier private, public, protected, default cho inner classes, và default hoặc public cho outer class.
Có hai loại chính nested class:
- Static Nested Class (Lớp lồng tĩnh)
- Non-Static Nested Class (Lớp lồng không tĩnh) – còn gọi là Inner Class
1. Static Nested Class
- Định nghĩa inner class với từ khóa static.
- Không chia sẻ mối quan hệ với instance của outer class.
- Chỉ truy cập được static members của outer class.
- Khởi tạo:
OuterClass.StaticNestedClass nested = new OuterClass.StaticNestedClass();
Ví dụ Static Nested Class
class Car {
static class Wheel {
public void rotate() {
System.out.println("The wheel is rotating");
}
}
}
public class Test {
public static void main(String args[]) {
Car.Wheel wheel = new Car.Wheel();
wheel.rotate();
}
}
Kết quả
The wheel is rotating
2. Non-Static Nested Class (Inner Class)
- Liên kết với object của outer class. Được đối xử như biến/phương thức của outer class.
- Vì liên kết với instance outer class, KHÔNG thể khai báo static variable/method bên trong (trừ hằng số compile-time constant).
- Khởi tạo:
OuterClass outer = new OuterClass(); OuterClass.InnerClass inner = outer.new InnerClass(); - Có thể truy cập tất cả member (private cũng được) của outer class.
Ví dụ Inner Class
public class OuterClassTest {
private int a = 10;
public void innerClassInstance() {
InnerClassTest inner = new InnerClassTest();
inner.outerObject();
}
public static void main(String args[]) {
OuterClassTest outer = new OuterClassTest();
outer.innerClassInstance();
}
class InnerClassTest {
public void outerObject() {
System.out.println("Outer Value of a is: " + a); // Truy cập private field của outer
}
}
}
Kết quả
Outer Value of a is: 10
Các loại Inner Class khác
| Loại | Vị trí | Đặc điểm |
|---|---|---|
| Member Inner Class | Trong class, ngoài method | Truy cập tất cả member outer, có thể private |
| Local Inner Class | Trong method/block | Chỉ nhìn thấy trong method, truy cập final/effectively final local variable |
| Anonymous Inner Class | Trong expression (new Interface() {...}) | Không tên, implement interface/extends class ngay lập tức |
| Đặc điểm | Static Nested Class | Inner Class (Non-static) |
|---|---|---|
| Truy cập outer instance member | Không | Có (kể cả private) |
| Cần outer instance để new | Không | Có (outer.new Inner()) |
| Có thể có static member | Có | Không (trừ constant) |
| Phạm vi truy cập outer | Chỉ static | Tất cả |