看板 java 關於我們 聯絡資訊
各位好,關於以下程式碼的執行結果,有些疑問: public class Parent { public String name = "Parent"; public void show() { System.out.println("I am Parent. "+this.name); } public static void main(String...args) { Parent.Son son = new Parent.Son(); Parent parent = son; System.out.println("the name of Son: "+son.name); System.out.println("the name of Parent: "+parent.name); son.show(); parent.show(); } static class Son extends Parent { public String name = "Son"; @Override public void show() { System.out.println("I am Son. "+this.name); } } } 執行結果: the name of Son: Son //son.name the name of Parent: Parent //parent.name I am Son. Son //son.show I am Son. Son //parent.show 我有問題的是,第二行的執行結果為何不是Son?我的想法是,雖然parent的型態為Paren t,但實際上卻是由Son所產生的,所以這邊的parent.name應該是指 Son類別的成員name才是。不曉得是我那裡的觀念有錯,煩請解惑,謝謝。 -- Sent from my Android -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.80.91.34 ※ 文章網址: http://www.ptt.cc/bbs/java/M.1407947421.A.533.html
cyclone350: field 沒有多型,method才有,這是規則 08/14 00:55
ssccg: 你可以看method上面有個@Override,name上面沒有 08/14 02:46
swpoker: 所以我認為OO的本質是行為阿 08/14 09:54
icydream: 了解,感謝各位回答 08/14 13:27