Re: [問題] private繼承問題

看板java作者 (有些事,有時候。。。)時間10年前 (2014/07/14 22:19), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串5/17 (看更多)
※ 引述《kiwatami (悠游自在)》之銘言: : ※ 引述《meya (落寞之心)》之銘言: : : class A{ : : private int a1=1; : : } : : public class test extends A{ : : public static void main(String[] args){ : : test t=new test(); : : System.out.println(t.a1); : : } : : } : : 子類別無法直接存取父類別的private a1,但 : : 究竟子類別有無繼承父類別的private a1? : : 應該用下列哪種理解才正確? : : (A)子類別內的a1繼承自父類別的a1,只是父類別用private修飾a1,讓其他類別無法直接 : : 存取父類別內的a1 : : (B)使用private修飾過的a1,無法被子類別繼承 : : 懇請回答謝謝 : 答案是A : 當然有被繼承 : 不然你用get會拿到什麼? : 用private只是封裝變數不給外部使用 : 用意是在外部程式若隨便更改變數可能會導致程式出現錯誤(當然這不是唯一的目的) : 所以要封裝起來由setter做更動 : 不一定正確啦 因為我滿討厭讀定義的XD : 你參考一下 http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.2 Members of a class that are declared private are not inherited by subclasses of that class. Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared. -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.231.154.117 ※ 文章網址: http://www.ptt.cc/bbs/java/M.1405347570.A.D45.html
文章代碼(AID): #1Jm-Ror5 (java)
討論串 (同標題文章)
文章代碼(AID): #1Jm-Ror5 (java)