Inheritance: extends, super, and overriding · יורשות: extends, super, ועיכוב (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.
ירושית: בנייה על בסיס מחלקה
- ירושית מאפשרת למחלקה להשתמש בשדות ובשיטות של מחלקה אחרת.
- המחלקה עליה נבנתה היא מחלקת האב (ההורה); המחלקה החדשה היא מחלקת הבת (הילד).
- מחלקת בת היא סוג של מחלקת האב שלה:
DogהואAnimal.
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 וsuper
- כתוב
class Dog extends Animalכדי להפוך אתDogלמחלקת בת שלAnimal. Dogמקבל באופן אוטומטי כל שיטה ציבורית שלAnimal, כמוgetName().- בונה מחלקת בת קורא תחילה את בונה מחלקת האב עם
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.
הפרת שיטה
- מחלקת בת יכולה להפר שיטה שורשה: לתת לה את אותו חתימה, גוף חדש.
Dog'sspeak()מחליףAnimal'sspeak()עבורDogאובייקטים.- שיטות שהיא לא חופפת (כמו
getName()) עדיין מורשות ללא שינוי.
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() — הרחב, אל תחלף
- לעיתים תרצה את העבודה של ההורה עם מעט נוסף.
- בתוך החפיפה,
super.describe()מקריא את גרסת ה-סוג האב של השיטה. - לאחר מכן אתה מוסיף לתוצרתה במקום לכתוב אותה מחדש.
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: סוג נגזר מתאים למקום בו מצופה הסוג האב שלו
- מכיוון ש-
DogמהווהAnimal, ניתן לכתובAnimal a = new Dog("Spot");. - סוג המשתנה הוא
Animal, אך האובייקת עצמו הוא בפועלDog. - כלל "is-a" זה הוא מה שמאפשר את הלקציה הבאה — פולימורפיזם — להתקיים.
Common mistakes
super(...)must be the first line of a subclass constructor.- Add
@Overrideso the compiler catches a wrong signature.
טעויות נפוצות
super(...)חייב להיות השורה הראשונה בבונה של סוג נגזר.- הוסף
@Overrideכדי שהמترجم יזהה חתימה שגויה.
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.
כעת תנסו בעצמכם
- כל משימה מספקת לך מחלקה עליונה מוגמרת
Animal. כתוב או השלם את ה-מחלקה תת-מחלקה מתחתיה. - מבחן נסתר בונה את האובייקת שלך ובדוק גם התנהגות מורשת וגם חדשה.
- לחץ על הפעל להרכבה, ואז על בדוק תשובה. הקוד שלך רץ על השרת, ולכן גם ההפעלה הראשונה מהירה.
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. · מתחת ל-Animal המוגמר, כתוב מחלקה Cat שתרחיב את Animal. תן לה בונה Cat(String name) שמעביר את השם כלפי מעלה עם super(name). אל תוסיף דבר נוסף — Cat אמורה לקבל את getName() בחינם.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Complete the class Cow (it already extends Animal). Override speak() so a Cow returns "Moo" instead of the default. getName() must still work (inherited). · השלם את המחלקה Cow (היא כבר רוחבת את Animal). עכב את speak() כך ש-Cow תחזיר "Moo" במקום ברירת המחדל. getName() עדיין צריכה לעבוד (מועברת מהמחלקה ההורה).
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
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. · השלם את המחלקה Fish (היא כבר רוחבת את Animal). עכב את describe() כך שתחזיר את התיאור Animal גם ", and I can swim". השתמש בעבודה של ההורה על ידי קריאה ל-super.describe() — אל תכתוב את המשפט כולו מחדש.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.