נבנה על ידי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.

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • פולימורפיזם: "הרבה צורות":polymorphism: "Many forms":
  • טיפוס סטטי: הטיפוס של המשתנה, כפי שכתוב בקוד (Item b).static type: The variable's type as written in the code (Item b).
  • שלושת המשתנים הם מסוג Item, אבל כל אחד מצביע על עצם מסוג אחר.All three variables are of type Item, but each points to a different kind of object.
  • line() כתובה רק ב-Item, ובתוכה kind() ו-loanDays() נבחרות לפי העצם האמיתי (dynamic dispatch).line() is written only in Item, and inside it kind() and loanDays() are chosen by the real object (dynamic dispatch).
  • העצם הוא EBook, אבל המשתנה הוא Item, ול-Item אין getSizeMb.The object is an EBook, but the variable is an Item, and Item has no getSizeMb.
  • javac בודק לפי הטיפוס הסטטי ועוצר.javac checks by the static type and stops.
  • it instanceof EBook e בודק את הסוג ונותן משתנה e מסוג EBook, כך שמותר לקרוא ל-getSizeMb.it instanceof EBook e checks the type and gives a variable e of type EBook, so you may call getSizeMb.
  • בלי הבדיקה, המרה של Dvd הייתה זורקת ClassCastException.Without the check, a downcast of a Dvd would throw a ClassCastException.
  • שני המשתנים מצביעים על אותה מחרוזת, אבל what(o) בוחרת את what(Object): גרסה של overloading נבחרת בזמן קומפילציה, לפי הטיפוס הסטטי.Both variables point to the same string, but what(o) picks what(Object): an overload is chosen at compile time, by the static type.

מונחיםTerms

  • פולימורפיזםpolymorphism: "הרבה צורות": קוד שכתוב מול טיפוס ההורה (Item) עובד עם כל תת-מחלקה, וכל עצם מתנהג לפי הסוג האמיתי שלו."Many forms": code written against the parent type (Item) works with every subclass, and each object behaves according to its real type.
  • טיפוס סטטיstatic type: הטיפוס של המשתנה, כפי שכתוב בקוד (Item b). javac מרשה לקרוא רק למתודות שקיימות בטיפוס הזה.The variable's type as written in the code (Item b). javac lets you call only methods that exist in that type.
  • dynamic dispatchdynamic dispatch: בזמן ריצה, Java בוחרת את הגרסה של המתודה לפי הסוג האמיתי של העצם, לא לפי סוג המשתנה.At run time, Java picks the method version by the object's real type, not the variable's type.
  • המרה למטהdowncast: (EBook) item: אומרים ל-javac "תאמין לי, זה EBook". אם זה לא נכון, בזמן ריצה נזרקת ClassCastException.(EBook) item: telling javac "trust me, it's an EBook". If that's wrong, a ClassCastException is thrown at run time.
  • ClassCastExceptionClassCastException: החריגה כשממירים עצם לטיפוס שהוא לא: class Dvd cannot be cast to class EBook. בודקים קודם עם instanceof.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.
  • instanceof עם משתנהpattern instanceof: o instanceof Book other בודק את הטיפוס וגם נותן משתנה מוכן מהטיפוס הזה, בלי המרה ידנית (Java 16 ומעלה).o instanceof Book other checks the type and gives a ready variable of that type, with no manual cast (Java 16 and up).
  • פולימורפיזםpolymorphism: "הרבה צורות": קוד שכתוב מול טיפוס ההורה (Item) עובד עם כל תת-מחלקה, וכל עצם מתנהג לפי הסוג האמיתי שלו."Many forms": code written against the parent type (Item) works with every subclass, and each object behaves according to its real type.
  • טיפוס סטטיstatic type: הטיפוס של המשתנה, כפי שכתוב בקוד (Item b). javac מרשה לקרוא רק למתודות שקיימות בטיפוס הזה.The variable's type as written in the code (Item b). javac lets you call only methods that exist in that type.
  • dynamic dispatchdynamic dispatch: בזמן ריצה, Java בוחרת את הגרסה של המתודה לפי הסוג האמיתי של העצם, לא לפי סוג המשתנה.At run time, Java picks the method version by the object's real type, not the variable's type.
  • המרה למטהdowncast: (EBook) item: אומרים ל-javac "תאמין לי, זה EBook". אם זה לא נכון, בזמן ריצה נזרקת ClassCastException.(EBook) item: telling javac "trust me, it's an EBook". If that's wrong, a ClassCastException is thrown at run time.
  • ClassCastExceptionClassCastException: החריגה כשממירים עצם לטיפוס שהוא לא: class Dvd cannot be cast to class EBook. בודקים קודם עם instanceof.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.

Cheatsheet

משתנה אחד, הרבה צורותOne variable type, many forms
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());
instanceof עם משתנהinstanceof with a variable
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");
    }
}
overloading נבחר מוקדםOverloading is chosen early
Object o = "hello";
String s = "hello";
System.out.println(what(o) + " " + what(s) + " " + o.getClass().getSimpleName());

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
cannot find symbolהטיפוס הסטטי קובע מה מותרThe static type decides what's allowedcannot find symbol: ל-Item אין getSizeMb(). צריך קודם לבדוק שזה EBook.cannot find symbol: Item has no getSizeMb(). You must first check it's an EBook.
ClassCastExceptionצייד באגים: המרה עיוורתBug hunter: a blind castClassCastException בשורה 6: בסיבוב השני it הוא Dvd, וההמרה ל-EBook נכשלת.ClassCastException on line 6: in the second round it is a Dvd, and the cast to EBook fails.

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