Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Các loại nested class (lớp lồng) trong Java

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

Tóm tắt so sánh

LoạiVị tríĐặc điểm
Member Inner ClassTrong class, ngoài methodTruy cập tất cả member outer, có thể private
Local Inner ClassTrong method/blockChỉ nhìn thấy trong method, truy cập final/effectively final local variable
Anonymous Inner ClassTrong expression (new Interface() {...})Không tên, implement interface/extends class ngay lập tức
Đặc điểmStatic Nested ClassInner Class (Non-static)
Truy cập outer instance memberKhôngCó (kể cả private)
Cần outer instance để newKhôngCó (outer.new Inner())
Có thể có static memberCóKhông (trừ constant)
Phạm vi truy cập outerChỉ staticTất cả