Đóng gói — Kế thừa — Đa hình — Trừu tượng (Encapsulation, Inheritance, Polymorphism, Abstraction).
- Đóng gói (Encapsulation): gom dữ liệu + method thao tác vào cùng class; ẩn nội bộ qua
private, chỉ lộ method nghiệp vụ. Hình dung: chai thuốc có nhãn — bạn không cần biết công thức để uống đúng liều. - Kế thừa (Inheritance): class con
extendsclass cha, dùng lại field + method.Dog extends Animal→ có sẵnname,eat(). Lưu ý: kế thừa gây coupling chặt — ưu tiên composition khi có thể. - Đa hình (Polymorphism): một interface, nhiều hành vi. Compile-time = overloading; runtime = overriding (
Animal a = new Dog(); a.speak()gọi bản của Dog). - Trừu tượng (Abstraction): lộ "làm được gì", giấu "làm thế nào". Hiện thực qua abstract class hoặc interface. Hình dung: tài xế biết quay vô-lăng, không cần hiểu hộp số.
Bốn tính chất gắn kết nhau: Trừu tượng đặt ra contract → Đóng gói giấu chi tiết → Kế thừa dùng lại → Đa hình thay implementation. Mục đích chung: giảm coupling, dễ test, dễ sửa.
Encapsulation — Inheritance — Polymorphism — Abstraction.
- Encapsulation: bundle data + the methods operating on it; hide internals via
private, expose only business methods. Picture a labelled medicine bottle — you do not need the formula to take the right dose. - Inheritance: a child class
extendsa parent, inheriting fields + methods.Dog extends Animal→ already hasname,eat(). Caveat: tight coupling — favour composition when possible. - Polymorphism: one interface, many behaviours. Compile-time = overloading; runtime = overriding (
Animal a = new Dog(); a.speak()calls the Dog version). - Abstraction: expose what it does, hide how. Implemented via abstract classes or interfaces. Picture a driver who steers and pedals without knowing the gearbox.
The four connect: Abstraction sets contracts → Encapsulation hides details → Inheritance reuses → Polymorphism swaps implementations. The goal: reduce coupling, increase testability/changeability.