Re: [J2SE] 多型與轉型
※ 引述《forris (喬巴)》之銘言:
: class Father{
: String name = "Father";
: String getName(){
: return name;
: }
: String greeting(){
: return "class Father";
: }
: }
: class Son extends Father{
: String name = "Son";
: String greeting(){
: return "class Son";
: }
public static void main ( String[] args ) {
Father father = new Son();
System.out.print( father.greeting() );
System.out.print( father.name );
System.out.print( father.getName() );
}
: }
想請問在main裡的程式,
輸出的結果是 class Son , Father , Father
爬文後小弟對於輸出的結果有些不了解,想請問各位小弟的觀念哪裡有問題?
Father father = new Son() ; <== 一個叫作father的東西,長得像Father,
但實體是Son。
所以第一個print ( father.greeting() ) ; 會去找Son裡面的greeting(),
(因為實體是son嘛),也因此印出來的東西是 class Son。
第三個print ( father.getName() ); 會去Son裡找getName(),但由於Son裡沒有,
所以會去父類別裡找getName(),因此印出來是Father。
不過第二個,為什麼不是在Son裡面找name,而是去Father裡面找name呢?
是因為屬性和方法是不一樣的做法嗎? 還是小弟我的觀念有問題?
煩請各位高手幫我解答一下,感恩!
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 210.241.0.157
→
07/14 17:50, , 1F
07/14 17:50, 1F
→
07/15 09:07, , 2F
07/15 09:07, 2F
→
07/15 09:34, , 3F
07/15 09:34, 3F
→
07/15 09:36, , 4F
07/15 09:36, 4F
→
07/17 16:54, , 5F
07/17 16:54, 5F
討論串 (同標題文章)