Apple מגדירה equals(Apple other) — פרמטר מהטיפוס הספציפי, כלומר העמסה (מתקיימת זו-לצד-זו עם equals(Object) שנשארת בירושה כמות שהיא). Banana מגדירה equals(Object other) — אותה חתימה בדיוק כמו Object.equals, כלומר דריסה אמיתית שמחליפה את ברירת המחדל.
Apple מגדירה equals(Apple other) — פרמטר מהטיפוס הספציפי, כלומר העמסה (מתקיימת זו-לצד-זו עם equals(Object) שנשארת בירושה כמות שהיא). Banana מגדירה equals(Object other) — אותה חתימה בדיוק כמו Object.equals, כלומר דריסה אמיתית שמחליפה את ברירת המחדל.
public class Apple {
private int weight;
public Apple (int w) {
weight = w;
}
public int getWeight () {
return weight;
}
public boolean equals(Apple other) {
return ((other!=null) &&
(weight == other.weight));
}
}
public class Banana {
private int weight;
public Banana (int w) {
weight = w;
}
public int getWeight () {
return weight;
}
public boolean equals (Object other) {
return ((other != null) &&
(other instanceof Banana) &&
(weight == ((Banana)other).weight));
}
}
האם קיימת העמסה (Overloading) או דריסה (Overriding) של הפעולה equals במחלקות Apple ו-Banana? הסבירו את תשובתכם.
נתונה המחלקה Program הבאה: public class Program { public static void main (String[] args) { System.out.println ("************"); Apple a1 = new Apple (10); Object a2 = new Apple (10); Banana b1 = new Banana (10); Object b2 = new Banana (10); ******* } } בהתייחס לכל אחת מהשורות הבאות, כתבו מה יקרה בעקבות הוספתה לשיטה main שלעיל (לאחר ההצהרות על האובייקטים, במקום שמסומן בכוכביות). הערה: אם הוספת פקודת קוד גורמת לשגיאה יש להסביר מהי השגיאה (שגיאת קומפילציה או שגיאת זמן ריצה).
- System.out.println (a1.weight);
- System.out.println (((Banana)a2).getWeight());
- System.out.println (a1.equals(a2));
- System.out.println (a2.equals(a1));
- System.out.println (b1.equals(b2));
- System.out.println (b2.equals(b1));
- System.out.println (a1.equals((Banana)b2));
- System.out.println (a1.equals((Apple)a2));
- System.out.println (b1.equals((Apple)a2));
- System.out.println (b1.equals((Banana)a2));
שאלות ותגובות על השאלה
🎓 לא הבנתם משהו? קבלו הסבר נוסף ממרצה לתכנות
שאלו כאן — ותקבלו מענה מוסמך.