אתם מתרגלים שאלה מתוך בגרות מדעי המחשב — מבני נתונים (שאלון 899271)מבחן 2022 · קיץ מועד א · שאלה 17כל שאלות המבחן ←
תכנות מונחה עצמיםפולימורפיזם ומחלקות מופשטות

נתונות שלוש מחלקות: Mammal (יונק), Antelope (אנטילופה, יורשת מ-Mammal) ו-Beaver (בונה, יורשת מ-Mammal). המחלקה Program נמצאת בחבילה (Package) שונה מהמחלקה Mammal. יש לזהות עבור כל אחת מהשורות 1–10 בפעולה main האם היא תגרום לשגיאת קומפילציה, ואם לא — מה הפלט (או שגיאת ריצה).

public class Mammal {
    protected int weight;
    public Mammal (int w) { weight = w; }
    public int GetWeight () { return weight; }
    public virtual bool IsSame (Mammal other) {
        Console.WriteLine ("In Mammal");
        return (this == other);
    }
}
public class Antelope : Mammal {
    public Antelope (int w) : base (w) { }
    public bool IsSame(Antelope other) {
        Console.WriteLine ("In Antelope");
        return ((other != null) && (this.weight == other.weight));
    }
}
public class Beaver : Mammal {
    public Beaver (int w) : base (w) { }
    public override bool IsSame (Mammal other) {
        Console.WriteLine ("In Beaver");
        return ((other != null) && (other is Beaver) && (this.weight == ((Beaver)other).weight));
    }
}
// Program is in a DIFFERENT package (namespace) from Mammal:
public class Program {
    public static void Main (string[] args) {
        Antelope a1 = new Antelope (10);
        object a2 = new Antelope (10);
        Beaver b1 = new Beaver (10);
        Mammal b2 = new Beaver (10);
        // ... statements 1-10 below
    }
}

// statements to analyze (same numbering):
1. System.out.println(a1.weight);
2. System.out.println(((Beaver)a2).getWeight());
3. System.out.println(a1.isSame(a2));
4. System.out.println(a2.isSame(a1));
5. System.out.println(b1.isSame(b2));
6. System.out.println(b2.isSame(b1));
7. System.out.println(a1.isSame((Beaver)b2));
8. System.out.println(a1.isSame((Antelope)a2));
9. System.out.println(b1.isSame((Antelope)a2));
10. System.out.println(b1.isSame((Beaver)a2));
סעיף א

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

שאלות ותגובות על השאלה

🎓 לא הבנתם משהו? קבלו הסבר נוסף ממרצה לתכנות

שאלו כאן — ותקבלו מענה מוסמך.

🎓 מרצה לתכנות עונה כאן — תקבלו מענה מקצועי