Re: [J2SE] private method在subclass內的表現

看板java作者 (菜英文沒有18%%)時間4年前 (2019/07/07 02:01), 編輯推噓0(005)
留言5則, 3人參與, 4年前最新討論串1/1
※ 引述《minGW128 (minGW128)》之銘言: : 各位好: : 最近在課本上看到一個範例,自己試著打了一下 : 對於最後的結果有些疑,po上來問請問一下大家 : code: : public class Test { : public static void main(String[] args) { : new Person().printPerson(); // Person : new Student().printPerson(); // Person : } : } : class Student extends Person { : private String getInfo() { : return "Student"; : } : } : class Person { : private String getInfo() { : return "Person"; : } : public void printPerson() { : System.out.println(getInfo()); : } : } : result: : Person : Person : 問題: : 簡單來說,Student繼承Person,由於printPerson()是public : 所以class Student內有繼承到printPerson() : 但是getInfo()在Person內是private,所以class Student內沒有繼承到getInfo() : 於是class Student內自行定義了一個自己的getInfo() : 然後呼叫new Student().printPerson() : printPerson()內會去呼叫getInfo()函數 : 請問為什麼呼叫的getInfo()函數 : 不是class Student內自行定義的getInfo() : 而是其superclass Person內的getInfo()呢? : 謝謝! 可以請教各位大大嗎 這題我看下面留言的解釋還是不太懂(新手... 我一直有個點轉不過來 printperson 不是被class student繼承了 那student這個類別 應該可以使用 printperson方法吧?!那為何student類別裡的 getInfo方法 不能呼叫呢? 謝謝各位! ----- Sent from JPTT on my LGE LG-H930. -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 223.138.30.56 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/java/M.1562436062.A.B8C.html

07/07 04:52, 4年前 , 1F
person裡面的getInfo是private 所以student 裡面的get
07/07 04:52, 1F

07/07 04:52, 4年前 , 2F
Info無法override
07/07 04:52, 2F

07/07 04:54, 4年前 , 3F
所以printperson裡面呼叫getInfo只會呼叫到person裡的
07/07 04:54, 3F

07/07 12:44, 4年前 , 4F
無法override 就沒有動態繫結的意思嗎
07/07 12:44, 4F

07/07 15:20, 4年前 , 5F
private若還可以overwrite,不就可怕了?還有private的意義嗎
07/07 15:20, 5F
文章代碼(AID): #1T8E7UkC (java)