חלק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.
הנקודות החשובות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 typeItem, but each points to a different kind of object. line()כתובה רק ב-Item, ובתוכהkind()ו-loanDays()נבחרות לפי העצם האמיתי (dynamic dispatch).line()is written only inItem, and inside itkind()andloanDays()are chosen by the real object (dynamic dispatch).- העצם הוא
EBook, אבל המשתנה הואItem, ול-ItemאיןgetSizeMb.The object is anEBook, but the variable is anItem, andItemhas nogetSizeMb. - javac בודק לפי הטיפוס הסטטי ועוצר.javac checks by the static type and stops.
it instanceof EBook eבודק את הסוג ונותן משתנהeמסוגEBook, כך שמותר לקרוא ל-getSizeMb.it instanceof EBook echecks the type and gives a variableeof typeEBook, so you may callgetSizeMb.- בלי הבדיקה, המרה של
Dvdהייתה זורקת ClassCastException.Without the check, a downcast of aDvdwould throw a ClassCastException. - שני המשתנים מצביעים על אותה מחרוזת, אבל
what(o)בוחרת אתwhat(Object): גרסה של overloading נבחרת בזמן קומפילציה, לפי הטיפוס הסטטי.Both variables point to the same string, butwhat(o)pickswhat(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, aClassCastExceptionis 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 withinstanceof. - instanceof עם משתנהpattern instanceof:
o instanceof Book otherבודק את הטיפוס וגם נותן משתנה מוכן מהטיפוס הזה, בלי המרה ידנית (Java 16 ומעלה).o instanceof Book otherchecks 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, aClassCastExceptionis 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 withinstanceof.
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 allowed | cannot 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 cast | ClassCastException בשורה 6: בסיבוב השני it הוא Dvd, וההמרה ל-EBook נכשלת.ClassCastException on line 6: in the second round it is a Dvd, and the cast to EBook fails. |