Inheritance: extends, super, and overriding · Kế thừa: extends, super, và overriding
Inheritance: building on a class
- Inheritance lets one class reuse another class's fields and methods.
- The class you build on is the superclass (parent); the new class is the subclass (child).
- A subclass is-a kind of its superclass: a
Dogis anAnimal.
Kế thừa: xây dựng dựa trên một class
- Kế thừa cho phép một class tái sử dụng các trường và phương thức của một class khác.
- Class mà bạn xây dựng dựa trên là superclass (cha); class mới là subclass (con).
- Một subclass là-a một loại của superclass: một
Doglà mộtAnimal.
extends and super
- Write
class Dog extends Animalto makeDoga subclass ofAnimal. Dogautomatically gets every public method ofAnimal, likegetName().- The subclass constructor calls the superclass constructor first with
super(...).
extends và super
- Viết
class Dog extends Animalđể khiếnDogtrở thành subclass củaAnimal. Dogtự động nhận được mọi public method củaAnimal, nhưgetName().- Constructor của subclass gọi constructor của superclass trước với
super(...).
public class Main {
public static void main(String[] args) {
Dog d = new Dog("Rex");
System.out.println(d.getName()); // Rex (inherited from Animal)
System.out.println(d.speak()); // Woof (Dog's own version)
}
}
class Animal {
private String name;
public Animal(String name) { this.name = name; }
public String getName() { return this.name; }
public String speak() { return "some sound"; }
}
class Dog extends Animal {
public Dog(String name) {
super(name); // run Animal's constructor
}
public String speak() { // override Animal's speak()
return "Woof";
}
}
Overriding a method
- A subclass can override an inherited method: give it the same signature, a new body.
Dog'sspeak()replacesAnimal'sspeak()forDogobjects.- Methods it does not override (like
getName()) are still inherited unchanged.
Ghi đè một method
- Một subclass có thể ghi đè một method được kế thừa: cung cấp cùng signature, một thân mới.
Dog'sspeak()thay thếAnimal'sspeak()cho các đối tượngDog.- Các method mà nó không ghi đè (như
getName()) vẫn được kế thừa nguyên vẹn.
super.method() — extend, don't replace
- Sometimes you want the parent's work plus a little more.
- Inside an override,
super.describe()runs the superclass version of the method. - Then you add to its result instead of rewriting it from scratch.
super.method() — kế thừa, không thay thế
- Đôi khi bạn muốn công việc của parent cộng thêm một chút nữa.
- Bên trong một method ghi đè,
super.describe()chạy phiên bản superclass của method đó. - Sau đó bạn bổ sung vào kết quả của nó thay vì viết lại từ đầu.
public class Main {
public static void main(String[] args) {
Bird b = new Bird("Tweety");
System.out.println(b.describe());
// I am an animal named Tweety, and I can fly
}
}
class Animal {
private String name;
public Animal(String name) { this.name = name; }
public String describe() { return "I am an animal named " + this.name; }
}
class Bird extends Animal {
public Bird(String name) { super(name); }
public String describe() {
return super.describe() + ", and I can fly"; // reuse, then add
}
}
is-a: a subclass fits where its superclass is expected
- Because a
Dogis anAnimal, you can writeAnimal a = new Dog("Spot");. - The variable's type is
Animal, but the object is really aDog. - This "is-a" rule is what makes the next lesson — polymorphism — possible.
is-a: một subclass phù hợp ở nơi superclassList expected
- Vì một
Doglà mộtAnimal, bạn có thể viếtAnimal a = new Dog("Spot");. - Type của biến là
Animal, nhưng đối tượng thực sự là mộtDog. - Quy tắc "is-a" này chính là thứ khiến bài học tiếp theo — polymorphism — có thể xảy ra.
Common mistakes
super(...)must be the first line of a subclass constructor.- Add
@Overrideso the compiler catches a wrong signature.
Lỗi thường gặp
super(...)phải là dòng đầu tiên của constructor subclass.- Thêm
@Overrideđể trình biên dịch phát hiện ra signature sai.
Now you try
- Each task gives you a finished
Animalsuperclass. Write or complete the subclass below it. - A hidden Harness builds your object and checks both inherited and new behaviour.
- Press Run to compile, then Check answer. Your code runs on the server, so even the first run is fast.
Bây giờ bạn thử
- Mỗi bài tập cung cấp cho bạn một superclass
Animalđã hoàn thiện. Hãy viết hoặc hoàn thành subclass bên dưới nó. - Một Harness ẩn tạo đối tượng của bạn và kiểm tra cả hành vi được kế thừa lẫn mới.
- Nhấn Run để biên dịch, sau đó Check answer. Mã của bạn chạy trên server, vì vậy ngay cả lần chạy đầu tiên cũng rất nhanh.
Below the finished Animal, write a class Cat that extends Animal. Give it a constructor Cat(String name) that passes the name up with super(name). Add nothing else — Cat should inherit getName() for free. · Dưới phần hoàn thành Animal, viết một class Cat mà extends Animal. Cung cấp cho nó một constructor Cat(String name) truyền tên lên trên với super(name). Không thêm gì khác — Cat sẽ thừa kế getName() miễn phí.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
Complete the class Cow (it already extends Animal). Override speak() so a Cow returns "Moo" instead of the default. getName() must still work (inherited). · Hoàn thành class Cow (nó đã kế thừa Animal). Override speak() sao cho một Cow trả về "Moo" thay vì giá trị mặc định. getName() vẫn phải hoạt động (được kế thừa).
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
Complete the class Fish (it already extends Animal). Override describe() so it returns the Animal description plus ", and I can swim". Reuse the parent's work by calling super.describe() — do not rewrite the whole sentence. · Hoàn thành class Fish (nó đã kế thừa Animal). Override describe() để trả về mô tả Animal cộng thêm ", and I can swim". Tái sử dụng công việc của cha bằng cách gọi super.describe() — không viết lại toàn bộ câu.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.