A: תכונה מוגנת x, שלושה בנאים (ללא פרמטרים→5, עם x, ועם x,y→this(x+y)), method(i)=x+i, toString="x * ". B יורשת מ-A, מוסיפה y, שלושה בנאים (עם x→super(x,x);y=x, עם x,y→this(x*y), עם String→מדפיס בגוף), toString="x y".
A: תכונה מוגנת x, שלושה בנאים (ללא פרמטרים→5, עם x, ועם x,y→this(x+y)), method(i)=x+i, toString="x * ". B יורשת מ-A, מוסיפה y, שלושה בנאים (עם x→super(x,x);y=x, עם x,y→this(x*y), עם String→מדפיס בגוף), toString="x y".
public class A {
protected int x;
public A(){ this.x = 5; }
public A(int x) { this.x = x; }
public A(int x, int y) { this(x + y); }
public int method(int i) { return x + i; }
public String toString() { return this.x + " * "; }
}
public class B extends A {
private int y;
public B(int x) { super(x, x); this.y = x; }
public B(int x, int y) { this(x * y); }
public B(String s) { System.out.println(s + "% " + this.y); }
public String toString() { return this.x + " " + this.y; }
}
public class Test {
public static void main(String[] args) {
A a1 = new B(4, 2);
System.out.println(a1);
A a2 = new A(4, 2);
System.out.println(a2);
B a3 = new B(4, 2);
System.out.println(a3);
A b1 = new A();
System.out.println(b1);
A c1 = new B("something");
System.out.println(c1);
}
}
סעיף א
עקבו אחרי ביצוע הפעולה הראשית ורשמו מה יהיה הפלט. יש להראות את העצמים שנוצרו ואת ערכי התכונות שלהם.
סעיף ב
לכל אחת מהפעולות הבאות קבעו אם אפשר להוסיף אותה במחלקה A, וציינו את האפשרות המתאימה: שגיאת קומפילציה / קוד תקין-דריסה (overriding) / קוד תקין-העמסה (overloading).
- public int method() { return 1; }
- public double method(int i) { return i; }
- public void method(double i) { System.out.print(i); } (C#: אותן שלוש, כשה-method בכותרת A מסומן public virtual int Method(int i), והתוספות הן virtual: public virtual int Method(), public virtual double Method(int i), public virtual void Method(double i).)
סעיף ג
אין קשר לסעיף ב'. לכל אחת מהפעולות הבאות קבעו אם אפשר להגדיר אותה במחלקה B, וציינו את האפשרות המתאימה: שגיאת קומפילציה / קוד תקין-דריסה (overriding) / קוד תקין-העמסה (overloading).
- public int method() { return 10; }
- public int method(int i) { return i*10; }
- public void method(int i) { System.out.print(10i); } (C#: public override int Method() { return 10; } / public override int Method(int i) { return i10; } / public override void Method(int i) { Console.Write(10*i); } — עם override.)
שאלות ותגובות על השאלה
🎓 לא הבנתם משהו? קבלו הסבר נוסף ממרצה לתכנות
שאלו כאן — ותקבלו מענה מוסמך.