נתונות שלוש מחלקות: Mammal (יונק), Antelope (אנטילופה, יורשת מ-Mammal) ו-Beaver (בונה, יורשת מ-Mammal). המחלקה Program נמצאת במרחב שמות (namespace) שונה מזה של המחלקה Mammal. יש לזהות עבור כל אחת מהשורות 1–10 בפעולה Main האם היא תגרום לשגיאת קומפילציה, ואם לא — מה הפלט (או שגיאת ריצה).
נתונות שלוש מחלקות: Mammal (יונק), Antelope (אנטילופה, יורשת מ-Mammal) ו-Beaver (בונה, יורשת מ-Mammal). המחלקה Program נמצאת במרחב שמות (namespace) שונה מזה של המחלקה 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 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. Console.WriteLine(a1.weight);
2. Console.WriteLine(((Beaver)a2).GetWeight());
3. Console.WriteLine(a1.IsSame(a2));
4. Console.WriteLine(a2.IsSame(a1));
5. Console.WriteLine(b1.IsSame(b2));
6. Console.WriteLine(b2.IsSame(b1));
7. Console.WriteLine(a1.IsSame((Beaver)b2));
8. Console.WriteLine(a1.IsSame((Antelope)a2));
9. Console.WriteLine(b1.IsSame((Antelope)a2));
10. Console.WriteLine(b1.IsSame((Beaver)a2));
סעיף א
עבור כל אחת מהשורות 1–10 שלהלן, כתבו במחברת את מספר השורה וציינו אם היא תגרום לשגיאת קומפילציה (ואם כן, הסבירו מדוע), או אם היא תקין — כתבו את הפלט (או ציינו קריסה בזמן ריצה).
שאלות ותגובות על השאלה
🎓 לא הבנתם משהו? קבלו הסבר נוסף ממרצה לתכנות
שאלו כאן — ותקבלו מענה מוסמך.