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

Có thể khai báo constructor private trong Java không?

Có, chúng ta có thể khai báo constructor private. Nếu constructor là private, không thể tạo object của lớp từ bên ngoài. Dùng private constructor trong Singleton Design Pattern.

Điều kiện của Private Constructor

  • Private constructor không cho phép lớp bị subclass (kế thừa).
  • Private constructor không cho phép tạo object bên ngoài lớp.
  • Nếu tất cả phương thức là hằng số (constant methods) → dùng private constructor.
  • Nếu tất cả phương thức static → dùng private constructor.
  • Nếu cố extends lớp có private constructor → lỗi compile-time.

Ví dụ: Singleton Pattern

class SingletonObject { 
    private SingletonObject() { 
        System.out.println("In a private constructor"); 
    } 
    
    public static SingletonObject getObject() { 
        if (ref == null) 
            ref = new SingletonObject(); 
        return ref; 
    } 
    
    private static SingletonObject ref; 
} 

public class PrivateConstructorDemo { 
    public static void main(String args[]) { 
        SingletonObject sObj = SingletonObject.getObject(); 
    } 
}

Kết quả đầu ra

In a private constructor

Các trường hợp dùng Private Constructor

Lưu ý

  • Private constructor + tất cả member static → Utility Class (thường thêm final cho class).
  • Singleton thread-safe: dùng enum hoặc volatile + double-checked locking.
Trường hợpMô tả
SingletonĐảm bảo chỉ 1 instance toàn ứng dụng
Utility ClassChỉ chứa static method/field (java.lang.Math, Collections)
Factory MethodKiểm soát tạo object qua static factory method
Builder PatternConstructor private, tạo qua Builder class
Constants-only classChỉ chứa hằng số, không cần instance