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

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

פולימורפיזם ו-dynamic dispatchPolymorphism & dynamic dispatch

הפניה מטיפוס אחד ועצם מטיפוס אחר, איזו מתודה נבחרת בזמן ריצה, casting ו-instanceof.

A reference of one type and an object of another, which method is chosen at run time, casting and instanceof.

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

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

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

  • פולימורפיזם: "הרבה צורות": קוד שכתוב מול טיפוס ההורה (Item) עובד עם כל תת-מחלקה, וכל עצם מתנהג לפי הסוג האמיתי שלו.polymorphism: "Many forms": code written against the parent type (Item) works with every subclass, and each object behaves according to its real type.
  • טיפוס סטטי: הטיפוס של המשתנה, כפי שכתוב בקוד (Item b). javac מרשה לקרוא רק למתודות שקיימות בטיפוס הזה.static type: The variable's type as written in the code (Item b). javac lets you call only methods that exist in that type.
  • dynamic dispatch: בזמן ריצה, Java בוחרת את הגרסה של המתודה לפי הסוג האמיתי של העצם, לא לפי סוג המשתנה.dynamic dispatch: At run time, Java picks the method version by the object's real type, not the variable's type.
  • המרה למטה: (EBook) item: אומרים ל-javac "תאמין לי, זה EBook". אם זה לא נכון, בזמן ריצה נזרקת ClassCastException.downcast: (EBook) item: telling javac "trust me, it's an EBook". If that's wrong, a ClassCastException is thrown at run time.
  • ClassCastException: החריגה כשממירים עצם לטיפוס שהוא לא: class Dvd cannot be cast to class EBook. בודקים קודם עם instanceof.ClassCastException: The exception when you cast an object to a type it isn't: class Dvd cannot be cast to class EBook. Check first with instanceof.

02משתנה אחד, הרבה צורותOne variable type, many forms

שלושת המשתנים הם מסוג Item, אבל כל אחד מצביע על עצם מסוג אחר. line() כתובה רק ב-Item, ובתוכה kind() ו-loanDays() נבחרות לפי העצם האמיתי (dynamic dispatch). צפו בסימולציה: מ-line קופצים ל-kind של EBook.

All three variables are of type Item, but each points to a different kind of object. line() is written only in Item, and inside it kind() and loanDays() are chosen by the real object (dynamic dispatch). Watch the simulation: from line it jumps to EBook's kind.

Main.java
public class Main {
    public static void main(String[] args) {
        Item a = new Item("Emma");
        Item b = new EBook("Dune", 2);
        Item c = new Dvd("Alien");
        System.out.println(a.line());
        System.out.println(b.line());
        System.out.println(c.line());
    }
}

class Item {
    protected final String title;

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

    String kind() {
        return "item";
    }

    int loanDays() {
        return 14;
    }

    String line() {
        return title + " (" + kind() + ", " + loanDays() + " days)";
    }
}

class EBook extends Item {
    private final int sizeMb;

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

    int getSizeMb() {
        return sizeMb;
    }

    @Override
    String kind() {
        return "ebook";
    }

    @Override
    int loanDays() {
        return 21;
    }
}

class Dvd extends Item {
    Dvd(String title) {
        super(title);
    }

    @Override
    String kind() {
        return "dvd";
    }

    @Override
    int loanDays() {
        return 3;
    }
}
פלטOutput
Emma (item, 14 days)
Dune (ebook, 21 days)
Alien (dvd, 3 days)
צפו בהרצה צעד אחר צעד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

03הטיפוס הסטטי קובע מה מותרThe static type decides what's allowed

העצם הוא EBook, אבל המשתנה הוא Item, ול-Item אין getSizeMb. javac בודק לפי הטיפוס הסטטי ועוצר.

The object is an EBook, but the variable is an Item, and Item has no getSizeMb. javac checks by the static type and stops.

טעות נפוצהCommon mistake

הטיפוס הסטטי קובע מה מותר

The static type decides what's allowed

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

class Item {
    protected final String title;

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

    String kind() {
        return "item";
    }

    int loanDays() {
        return 14;
    }

    String line() {
        return title + " (" + kind() + ", " + loanDays() + " days)";
    }
}

class EBook extends Item {
    private final int sizeMb;

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

    int getSizeMb() {
        return sizeMb;
    }

    @Override
    String kind() {
        return "ebook";
    }

    @Override
    int loanDays() {
        return 21;
    }
}

class Dvd extends Item {
    Dvd(String title) {
        super(title);
    }

    @Override
    String kind() {
        return "dvd";
    }

    @Override
    int loanDays() {
        return 3;
    }
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
Main.java:4: error: cannot find symbol
        System.out.println(b.getSizeMb());
                            ^
  symbol:   method getSizeMb()
  location: variable b of type Item
1 error
בעברית פשוטה: In plain words: cannot find symbol: ל-Item אין getSizeMb(). צריך קודם לבדוק שזה EBook.cannot find symbol: Item has no getSizeMb(). You must first check it's an EBook.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

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

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

מסך הפלטOutput screen

04instanceof עם משתנהinstanceof with a variable

it instanceof EBook e בודק את הסוג ונותן משתנה e מסוג EBook, כך שמותר לקרוא ל-getSizeMb. בלי הבדיקה, המרה של Dvd הייתה זורקת ClassCastException.

it instanceof EBook e checks the type and gives a variable e of type EBook, so you may call getSizeMb. Without the check, a downcast of a Dvd would throw a ClassCastException.

Main.java
public class Main {
    public static void main(String[] args) {
        Item[] items = {new EBook("Dune", 2), new Dvd("Alien")};
        for (Item it : items) {
            if (it instanceof EBook e) {
                System.out.println(e.title + ": " + e.getSizeMb() + " MB");
            } else {
                System.out.println(it.title + ": not an ebook");
            }
        }
    }
}

class Item {
    protected final String title;

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

    String kind() {
        return "item";
    }

    int loanDays() {
        return 14;
    }

    String line() {
        return title + " (" + kind() + ", " + loanDays() + " days)";
    }
}

class EBook extends Item {
    private final int sizeMb;

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

    int getSizeMb() {
        return sizeMb;
    }

    @Override
    String kind() {
        return "ebook";
    }

    @Override
    int loanDays() {
        return 21;
    }
}

class Dvd extends Item {
    Dvd(String title) {
        super(title);
    }

    @Override
    String kind() {
        return "dvd";
    }

    @Override
    int loanDays() {
        return 3;
    }
}
פלטOutput
Dune: 2 MB
Alien: not an ebook
צפו בהרצה צעד אחר צעד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

05overloading נבחר מוקדםOverloading is chosen early

שני המשתנים מצביעים על אותה מחרוזת, אבל what(o) בוחרת את what(Object): גרסה של overloading נבחרת בזמן קומפילציה, לפי הטיפוס הסטטי. רק overriding נבחר בזמן ריצה.

Both variables point to the same string, but what(o) picks what(Object): an overload is chosen at compile time, by the static type. Only overriding is chosen at run time.

Main.java
public class Main {
    static String what(Object o) {
        return "Object";
    }

    static String what(String s) {
        return "String";
    }

    public static void main(String[] args) {
        Object o = "hello";
        String s = "hello";
        System.out.println(what(o) + " " + what(s) + " " + o.getClass().getSimpleName());
    }
}
פלטOutput
Object String String
צפו בהרצה צעד אחר צעד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

06טעויות נפוצות, ומה 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

צייד באגים: המרה עיוורת

Bug hunter: a blind cast

Main.java
public class Main {
    public static void main(String[] args) {
        Item[] items = {new EBook("Dune", 2), new Dvd("Alien")};
        int total = 0;
        for (Item it : items) {
            EBook e = (EBook) it;
            total += e.getSizeMb();
        }
        System.out.println("Total: " + total + " MB");
    }
}

class Item {
    protected final String title;

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

    String kind() {
        return "item";
    }

    int loanDays() {
        return 14;
    }

    String line() {
        return title + " (" + kind() + ", " + loanDays() + " days)";
    }
}

class EBook extends Item {
    private final int sizeMb;

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

    int getSizeMb() {
        return sizeMb;
    }

    @Override
    String kind() {
        return "ebook";
    }

    @Override
    int loanDays() {
        return 21;
    }
}

class Dvd extends Item {
    Dvd(String title) {
        super(title);
    }

    @Override
    String kind() {
        return "dvd";
    }

    @Override
    int loanDays() {
        return 3;
    }
}
מה Java עונה (התוכנית קורסת)What Java says (the program crashes)
Exception in thread "main" java.lang.ClassCastException: class Dvd cannot be cast to class EBook (Dvd and EBook are in unnamed module of loader 'app')
	at Main.main(Main.java:6)
בעברית פשוטה: In plain words: ClassCastException בשורה 6: בסיבוב השני it הוא Dvd, וההמרה ל-EBook נכשלת.ClassCastException on line 6: in the second round it is a Dvd, and the cast to EBook fails.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

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

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

מסך הפלטOutput screen

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

ב-List<Item> יש Emma (ספר), Dune (ebook), Alien (dvd) ו-Emma (ebook). הדפיסו שורה לכל פריט (Dune (ebook, 21 days)), וספרו כמה יש מכל סוג ב-TreeMap: {dvd=1, ebook=2, item=1}.

A List<Item> holds Emma (a book), Dune (ebook), Alien (dvd) and Emma (ebook). Print a line per item (Dune (ebook, 21 days)), and count each kind in a TreeMap: {dvd=1, ebook=2, item=1}.

טיפ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