נבנה על ידיBuilt by Ariel Yohimovich

JavaJava
19
חלקPart 4: OOP מתקדםAdvanced OOP כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

ירושה, super ו-overrideInheritance, super & override

extends, super() ו-super.method(), @Override, ומתי ירושה היא רעיון רע.

extends, super() and super.method(), @Override, and when inheritance is a bad idea.

01המונחים של המפגשThis session's terms

לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.

Before the code, the words. Every term here is also linked in the course glossary.

  • ירושה: class EBook extends Book: ל-EBook יש את כל השדות והמתודות של Book, והיא יכולה להוסיף ולשנות. לכל מחלקה הורה אחד בלבד.inheritance: class EBook extends Book: EBook has every field and method of Book, and can add and change. Each class has exactly one parent.
  • מחלקת על (הורה): המחלקה שממנה יורשים. מחלקה שלא כתוב לה extends יורשת מ-Object.superclass (parent): The class you inherit from. A class without extends inherits from Object.
  • super: super(...) בשורה הראשונה של בנאי קורא לבנאי של ההורה. super.describe() קורא לגרסה של ההורה מתוך מתודה שדורסת אותה.super: super(...) on a constructor's first line calls the parent's constructor. super.describe() calls the parent's version from inside a method that overrides it.
  • דריסה: מתודה בתת-מחלקה עם אותה חתימה בדיוק כמו בהורה, שמחליפה את ההתנהגות. @Override מבקש מ-javac לוודא שזו באמת דריסה.overriding: A method in a subclass with exactly the parent's signature, replacing the behaviour. @Override asks javac to make sure it really is an override.
  • protected: גישה למחלקה, לתת-המחלקות שלה ולמחלקות באותה חבילה. נוח, אבל חושף מימוש לכל מי שיורש.protected: Access for the class, its subclasses and classes in the same package. Handy, but it exposes the implementation to every subclass.
  • is-a מול has-a: ירושה מתאימה כשמשפט "X הוא סוג של Y" נכון תמיד (EBook הוא ספר). כש-X רק משתמש ב-Y, עדיף הרכבה (has-a): שדה מסוג Y.is-a vs has-a: Inheritance fits when "X is a kind of Y" is always true (an EBook is a book). When X only uses Y, prefer composition (has-a): a field of type Y.

02extends, super ו-@Overrideextends, super and @Override

EBook יורשת מ-Book: יש לה getTitle בלי לכתוב אותה. הבנאי שלה קורא קודם ל-super(title). describe נדרסת, ומשתמשת בגרסה של ההורה עם super.describe(). בזיכרון רואים עצם EBook אחד שמחזיק גם את title של ההורה.

EBook inherits from Book: it has getTitle without writing it. Its constructor first calls super(title). describe is overridden, and uses the parent's version with super.describe(). In memory you see one EBook object that holds the parent's title too.

Main.java
public class Main {
    public static void main(String[] args) {
        Book b = new Book("Emma");
        EBook e = new EBook("Dune", 2);
        System.out.println(b.describe());
        System.out.println(e.describe());
        System.out.println(e.getTitle());
    }
}

class Book {
    private final String title;

    Book(String title) {
        this.title = title;
    }

    String getTitle() {
        return title;
    }

    String describe() {
        return "Book: " + title;
    }
}

class EBook extends Book {
    private final int sizeMb;

    EBook(String title, int sizeMb) {
        super(title);
        this.sizeMb = sizeMb;
    }

    @Override
    String describe() {
        return super.describe() + " (" + sizeMb + " MB)";
    }
}
פלטOutput
Book: Emma
Book: Dune (2 MB)
Dune
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

ויזואלייזר זיכרוןMemory visualizerextends, super ו-@Overrideextends, super and @Override

מה קורה עכשיוWhat happens now

פלטOutput

Stack: משתנים בכל מתודהStack: each method's variables

Heap: העצמיםHeap: the objects

03כששוכחים את super(...)When you forget super(...)

אם בנאי לא קורא ל-super(...), Java מוסיפה super() ריק. ל-Book אין בנאי ריק, ולכן javac עוצר.

If a constructor doesn't call super(...), Java adds an empty super(). Book has no empty constructor, so javac stops.

טעות נפוצהCommon mistake

כששוכחים את super(...)

When you forget super(...)

Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println(new EBook(2).describe());
    }
}

class Book {
    final String title;

    Book(String title) {
        this.title = title;
    }

    String describe() {
        return title;
    }
}

class EBook extends Book {
    final int sizeMb;

    EBook(int sizeMb) {
        this.sizeMb = sizeMb;
    }
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
Main.java:22: error: constructor Book in class Book cannot be applied to given types;
    EBook(int sizeMb) {
                      ^
  required: String
  found:    no arguments
  reason: actual and formal argument lists differ in length
1 error
בעברית פשוטה: In plain words: constructor Book in class Book cannot be applied to given types;: ה-super() שנוסף לבד לא מתאים ל-Book(String).constructor Book in class Book cannot be applied to given types;: the super() added for you doesn't match Book(String).
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

04כשירושה היא רעיון רעWhen inheritance is a bad idea

Stack extends ArrayList נראה חסכוני, אבל עכשיו כל מי שמחזיק Stack יכול לקרוא ל-add(0, 99) ולשבור את הכלל "האחרון שנכנס יוצא ראשון". מחסנית היא לא סוג של רשימה, היא משתמשת ברשימה. באתגר 1 תתקנו את זה עם הרכבה.

Stack extends ArrayList looks economical, but now anyone holding a Stack can call add(0, 99) and break the rule "last in, first out". A stack isn't a kind of list, it uses a list. In challenge 1 you'll fix it with composition (has-a).

Main.java
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        Stack s = new Stack();
        s.push(1);
        s.push(2);
        s.add(0, 99);
        System.out.println(s.pop() + " " + s.pop() + " " + s.pop());
    }
}

class Stack extends ArrayList<Integer> {
    void push(int x) {
        add(x);
    }

    int pop() {
        return remove(size() - 1);
    }
}
פלטOutput
2 1 99
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

05טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says

אלה הטעויות שהתרגילים מהסוג "צייד באגים" בנויים סביבן. כל אחת רצה באמת, והפלט הוא מה ש-Java עונה.

These are the mistakes the "bug hunter" exercises are built around. Each one really runs, and the output is what Java says.

טעות נפוצהCommon mistake

צייד באגים: super חסר

Bug hunter: a missing super

Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println(new EBook(2).describe());
    }
}

class Book {
    final String title;

    Book(String title) {
        this.title = title;
    }

    String describe() {
        return title;
    }
}

class EBook extends Book {
    final int sizeMb;

    EBook(int sizeMb) {
        this.sizeMb = sizeMb;
    }
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
Main.java:22: error: constructor Book in class Book cannot be applied to given types;
    EBook(int sizeMb) {
                      ^
  required: String
  found:    no arguments
  reason: actual and formal argument lists differ in length
1 error
בעברית פשוטה: In plain words: constructor Book in class Book cannot be applied to given types;: הבנאי של EBook לא קרא ל-super, ו-Java ניסתה super() ריק שלא קיים.constructor Book in class Book cannot be applied to given types;: EBook's constructor didn't call super, so Java tried an empty super() that doesn't exist.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

06הצעד של היום בפרויקט מדףToday's step in the Shelf project

Book(title, author) עם describe() (Emma by Austen). EBook מוסיפה גודל (Dune by Herbert [ebook, 2 MB]), ו-AudioBook מוסיפה דקות (Ulysses by Joyce [audio, 1h 30m]). שתיהן משתמשות ב-super.describe(). הדפיסו את שלושתם.

Book(title, author) with describe() (Emma by Austen). EBook adds a size (Dune by Herbert [ebook, 2 MB]), and AudioBook adds minutes (Ulysses by Joyce [audio, 1h 30m]). Both use super.describe(). Print all three.

טיפTip

את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.

You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

נבנה על ידיBuilt by Ariel Yohimovich