看板 Grad-ProbAsk 關於我們 聯絡資訊
※ 引述《nickboy0211 (Silly Boy)》之銘言: : 此為java的inheritance觀念的題目,曾有試著自己key到電腦去run。 : 但一直compile錯誤,目前也沒時間debug了,希望會的大大能幫忙。謝謝。 : Given the java code fragment in the follow : a. what is the output of the program, while executing the "java Main" command? : 程式如下: : public class A{ : public void m1(){ : System.out.println("123"); : } : } : public class B extends A{ : public void m1(){ : System.out.println("456"); : } : } : public class Main{ : public void main(String[] args){ : A ref = new B(); <-----希望能解釋一下這一行,因new b 卻用a的型態??? : ref.m1(); : } : } 456 這是java的Polymorphism, 題目中A和B有相同命名的method, A ref = new B(); 因為B extend A,所以這樣宣告是可以的, 而ref.m1()就會去跑B裡面的method. 這是我的理解,有錯請指教。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.113.216.88
nickboy0211:感謝5566大大的幫忙。@@ 原來是多型。 02/21 15:54