Test.java
class MyObject {}
public class Test {
public static void main(String[] args) {
MyObject obj = new MyObject();
obj.clone(); // Compile error.
}
}
此時出現上文提到的錯誤:The method clone from the type Object is not visiuable.
同樣Test也是java.lang.Object的子類。但是,不能在一個子類中訪問另一個子類的protected方法,盡管這兩個子類繼承自同一個父類。
再看示例2:
Test2.java
class MyObject2 {
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Test2 {
public static void main(String[] args) throws CloneNotSupportedException {
MyObject2 obj = new MyObject2();
obj.clone(); // Compile OK.
}
}
這里,我們在MyObject2類中覆蓋(override)父類的clone()方法,在另一個類Test2中調用clone()方法,編譯通過。
編譯通過的原因顯而易見,當你在MyObject2類中覆蓋clone()方法時,MyObject2類和Test2類在同一個包下,所以此protected方法對Test2類可見。
分析到這里,我們在回憶一下Java中的淺復制與深復制文中,章節2.2中的聲明,②在派生類中覆蓋基類的clone()方法,并聲明為public。 現在明白這句話的原因了吧(為了讓其它類能調用這個類的clone()方法,重載之后要把clone()方法的屬性設置為public)。
下面再來看示例3:
Test3.java
package 1
class MyObject3 {
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
package 2
public class Test3 extends MyObject3 {
public static void main(String args[]) {
MyObject3 obj = new MyObject3();
obj.clone(); // Compile error.
Test3 tobj = new Test3();
tobj.clone();// Complie OK.
}
}
這里我用Test3類繼承MyObject3,注意這兩個類是不同包的,否則就是示例2的情形。在Test3類中調用Test3類的實例tobj的clone()方法,編譯通過。而同樣調用MyObject3類的實例obj的clone()方法,編譯錯誤!
意想不到的結果,protected方法不是可以被繼承類訪問嗎?
必須明確,類Test3確實是繼承了類MyObject3(包括它的clone方法),所以在類Test3中可以調用自己的clone方法。但類MyObject3的protected方法對其不同包子類Test3來說,是不可見的。
這里再給出《java in a nutshell》中的一段話:
protected access requires a little more elaboration. Suppose class A declares a protected field x and is extended by a class B, which is defined in a different package (this last point is important). Class B inherits the protected field x, and its code can access that field in the current instance of B or in any other instances of B that the code can refer to. This does not mean, however, that the code of class B can start reading the protected fields of arbitrary instances of A! If an object is an instance of A but is not an instance of B, its fields are obviously not inherited by B, and the code of class B cannot read them.
順便說兩句,國內的很多Java書籍在介紹訪問權限時,一般都這樣描述(形式各異,內容一致):
方法的訪問控制:
public | protected | default | private | |
同類 | T | T | T | T |
同包 | T | T | T | |
子類(不同包) | T | T | ||
不同包中無繼承關系的類 | T |
本文出自 “子 孑” 博客,請務必保留此出處http://zhangjunhd.blog.51cto.com/113473/19287