看板 java 關於我們 聯絡資訊
※ 引述《bleed1979 (十三)》之銘言: : ※ 引述《pzyc79 (I'm bored)》之銘言: : : ===============Class Test:=============== : : package a; : : public class Test { : : protected Test(){ : : } : : } : : ===============Class Test2:============== : : package b; : : import a.Test; : : public class Test2 extends Test{ : : void fun(){ : : Test t = new Test(); //Test() is not visible : : } : : } : : WHY? 宣告protected不是可以在子類別中看見嗎? : 前面的文章太多結果論了,回歸到定義面吧。 : http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html : Constructors are not members ... blabla ... : http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html : 這是作用在 members 上的。 : end 稍做補充 根據定義,連 call 方法也是不行的, 也就是在 Test2 中以下這行也會錯: // 假設 Test 有一個 public constructor // 並有一個 protected method new PublicConstructorOfTest().protectedMethod(); 因為 Test 並不是自己的 subclass, 不能在其它 package 中生一個 Test 的實體, 然後透過它來 call Test 的 protected 方法。 實測下來結果也是如此,參見 gist https://gist.github.com/anonymous/2d80bf9eb1581ed05fc6 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.226.196.214 ※ 文章網址: http://www.ptt.cc/bbs/java/M.1399775273.A.2D9.html ※ 編輯: lovdkkkk (36.226.196.214), 05/11/2014 10:29:09
lovdkkkk:貼完 github 馬上掛掉...0rz 05/11 10:37
sbrhsieh:都搞錯重點,跟 constructor 算不算 member 沒關係 05/11 20:35
sbrhsieh:跟 Test 是不是自己的 subclass 也沒關係。 05/11 20:36
sbrhsieh:new Test().protectedMethod(); 合不合格是看 statement 05/11 20:38
sbrhsieh:出現的context。不要往為什麼一個Test object 會不能執行 05/11 20:40
sbrhsieh:自己的 protected method 這方向硬要想一個理由。 05/11 20:41
我只是很單純的照官方文件說法去看 截錄: within its own package (as with package-private) and, in addition, by a subclass of its class in another package. 官方說明的就是這兩個條件 1. 在同 package 裡 call 2. 由 subclass call 所以我才會由 是不是同 package 或 是不是 subclass 去看 @@ ※ 編輯: lovdkkkk (36.226.196.214), 05/11/2014 21:22:42