我对保护标识符有一些疑问 . 在K.Sierra的Sun认证Java程序员学习指南的第一章中,我发现了以下信息:
"Once the subclass-outside-the-package inherits the protected member, that member (as inherited by the subclass) becomes private to any code outside the subclass, with the exception of subclasses of the subclass."
我提供了反映上述陈述的示例代码,对我来说绝对清楚 .
// Parent class
package package1;
import package2.Child;
public class Parent {
protected int i = 5;
}
// Child class
package package2;
import package1.Parent;
public class Child extends Parent {
// variable 'i' inherited
}
package package2;
public class Neighbour {
public void protectedTesting(){
Child child = new Child();
System.out.println(child.i); // no access
}
}
我已经开始尝试并进行了一些小改动 - 将Neighbor移到package1 . 并且可以访问"i"变量,这对我来说有点令人惊讶,因为它不符合声明 "becomes private to any code outside the subclass"
更改后的邻居类:
package package1;
import package2.Child;
public class Neighbour {
public void protectedTesting(){
Child child = new Child();
System.out.println(child.i); // access!
}
}
请向我澄清一下 . 谢谢 .
4 回答
简而言之,
protected
是包私有的,也是子类可见的 . 甚至JLS对此也很模糊(JLS §6.6.2):它指定在包外部,只有子类可以访问受保护的成员 . 这意味着您还可以访问包中的变量 . 它的措辞很差,但真正的是受保护的成员具有包级别可见性以及子类级别的可见性 .
也可以看看:
This related question
Java Trail用于访问控制
真相不在"Sun Certified Java Programmer Study Guide"但在Java Language Specification
protected
可见性包括包级别可见性 . 继承允许您将Child
对象视为Parent
的实例 . 由于Parent
的成员i
在同一个包中声明,因此可以从Neighbour
访问它 .