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书籍在介绍访问权限时,一般都这样描述(形式各异,内容一致):
方法的访问控制:
|
转载于:https://www.cnblogs.com/moonfans/archive/2012/08/08/2628485.html