Bạn kiểm soát thừa kế bằng cách tạo ra một hệ thống phân cấp thừa kế. Một khi bạn xác định
được các lớp học là superclasses và những lớp là lớp con của họ, thừa kế
tự động xảy ra.
Ví dụ, tất cả các tính năng của tài khoản cũng có mặt trong SavingsAccount,
CheckingAccount và MortgageAccount. Hình 2.5 mở rộng trên hình 2.4, cho thấy
một loạt các thuộc tính và các hoạt động sở hữu bởi tài khoản cũng sẽ được
thừa hưởng bởi ba lớp con. Các thuộc tính được thể hiện ở giữa lớp
hộp; hoạt động được hiển thị ở phía dưới. Các tính năng được thừa kế không
thể hiện rõ ràng trong các lớp con để làm cho sơ đồ rõ ràng hơn; Tuy nhiên, bất kỳ
tính năng mới độc quyền cho mỗi lớp con được hiển thị.
Tổ chức các lớp học vào phân cấp thừa kế là một kỹ năng quan trọng trong hướng đối tượng
thiết kế và lập trình. Nó rất dễ dàng để làm cho những sai lầm và tạo ra không hợp lệ
khái quát. Một trong những nguyên tắc quan trọng nhất để tuân thủ chính là quy tắc isa. Các
quy tắc isa nói rằng lớp A chỉ có thể là một lớp con của lớp B có giá trị nếu nó làm cho tinh thần,
bằng tiếng Anh, nói: "A là B '. Ví dụ nó làm cho tinh thần để nói 'một SavingsAccount
là một tài khoản "; nó không có ý nghĩa để nói nghịch đảo, 'một tài khoản là một
SavingsAccount'. Bạn nên kiểm tra tất cả các cặp cha-subclass (khái quát)
chống lại sự cai isa. Chính vì lý do này mà phân cấp thừa kế thường được
gọi là hệ thống phân cấp isa.
Khi bạn phát hiện một hành vi vi phạm các quy tắc isa, đó là một dấu hiệu rõ ràng rằng bạn đã
thực hiện một sự tổng quát không hợp lệ. Tuy nhiên, không phải tất cả các trường hợp quy tắc isa giữ
là những khái quát tốt. Điểm quan trọng khác, bạn nên kiểm tra là:
■ Nếu bạn có cho các lớp con hoặc tên lớp cha không rõ ràng (như 'xe buýt' như
mô tả ở trên), bạn sẽ thường tạo ra những khái quát xấu.
đang được dịch, vui lòng đợi..