Re: [問題] 在子類別new建構子為protected的父類別

作者: lovdkkkk (dk)   2014-05-11 10:27:48
※ 引述《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
作者: lovdkkkk (dk)   2014-05-11 10:37:00
貼完 github 馬上掛掉...0rz
作者: sbrhsieh (十年一夢)   2014-05-11 20:35:00
都搞錯重點,跟 constructor 算不算 member 沒關係跟 Test 是不是自己的 subclass 也沒關係。new Test().protectedMethod(); 合不合格是看 statement出現的context。不要往為什麼一個Test object 會不能執行自己的 protected method 這方向硬要想一個理由。

Links booklink

Contact Us: admin [ a t ] ucptt.com