若執行下列的 Java 程式碼,則螢幕上輸出的英文字母依序為何?
class Parent{
Parent(){
System.out.println('p');
}
}
class Child extends Parent{
Child(){
System.out.println('c');
}
}
public class ClassTest{
public static void main(String[] args){
Parent p = new Parent();
Child c = new Child();
Parent x = new Child();
}
}
Ap,c,c
Bp,c,p
Cp,p,c,p
Dp,p,c,p,c正確答案
答案與詳解
D
正確答案
Java 建構子呼叫時會先呼叫父類別建構子 (super()),故 new Child() 會先印 p 再印 c。
為什麼答案是 D
new Parent() 印 p;new Child() 先呼叫 super() 印 p 再印 c;Parent x = new Child() 同樣印 p、c。結果為 p, p, c, p, c。
載入中…
完整詳解
Pro · 無限
重點Java 建構子呼叫時會先呼叫父類別建構子 (super()),故 new Child() 會先印 p 再印 c。
秒殺技巧
每個 new 物件:先跑 Parent 建構子,再跑自己的建構子。Parent→p;Child→p+c。