אתם מתרגלים שאלה מתוך מה"ט מבני נתונים ותכנות מונחה עצמים — הנדסאי תוכנהמבחן 2023 · קיץ מועד א · שאלה 8כל שאלות המבחן ←
תכנות מונחה עצמים›פולימורפיזם ומחלקות מופשטות

java

public class A { public static int countA = 0; private String st; public A() { this.st = "aaa"; countA++;} public A(String st) { this.st = st; countA++;} public String toString() { return this.st; } public boolean same (Object obj) { if ((obj instanceof A) && (((A)obj).st.equals(this.st))) return true; return false; } } //end of class A

public class B extends A { public static int countB = 0; private int num; public B() { super(); this.num = 1; countB++; } public B(int num) { super(); this.num = num; countB++; } public B(int num, String st) { super(st); this.num = Math.abs(num); countB++; } public String toString() { String s = this.num +"/"; for(int i = 0; i< this.num; i++) s+=super.toString(); return s; } public boolean same (Object obj) { if ((obj instanceof B) && (((B)obj).num == this.num)) return true; return false; } } //end of class B

סעיף א

לפניכם קטע קוד מהתוכנית הראשית: A a = new A(); B b = new B(); if (a.same(b)) System.out.println(a); else System.out.println(b); if (b.same(a)) System.out.println(b); else System.out.println(a); מה יהיה הפלט של קטע התוכנית? הסבירו את תשובתכם.

סעיף ב

נתונה המחלקה Tester הבאה: public class Tester { public static void print (Object[] arr) { for (int i = 0; i < arr.length; i++) { if (arr[i] != null) { if (arr[i] instanceof B) System.out.println("B: " + arr[i]); else if (arr[i] instanceof A) System.out.println("A: " + arr[i]); else System.out.println("Unknown"); } else System.out.println("NULL"); } } public static void main (String[] args) { A[] ar1 = new A[7]; ar1[0] = new B(-4); ar1[1] = new A("bbb"); ar1[2] = new B(3,"ccc"); ar1[3] = new B(); ar1[4] = new B(2, "ddd"); ar1[5] = new A(); print(ar1); System.out.println(A.countA+ " "+ B.countB); } } //end of class Tester עקבו אחרי ביצוע תוכנית הראשית (main) ורשמו מה יהיה פלט התוכנית. יש להציג את התכונות של כל העצמים שנוצרו במהלך ביצוע התוכנית.

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

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

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

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