我学到的一件事是 private
在 java 中与在 C++ 中的意思并不相同。 java中的private
是基于类的,而不是基于对象的。
即我可以使用“对象点符号”直接访问另一个对象私有(private)成员前提是我在该对象的类中这样做。
但是,protected
就不是那么清楚了。
我们必须在这里考虑两个包:pack1
和 pack2
我们在pack1
包
中声明类Alpha
和Beta
并声明从 pack1
扩展 Alpha
的 AlphaSub
和从 Alpha 扩展的
在 Gamma
pack2
包中。
!
这是类代码,我在这里只包含与问题相关的类:Alpha
、AlphaSub
和 Gamma
package pack1;
public class Alpha{
private int alphaPrivate;
public int alphaPublic;
protected int alphaProtected;
int alphaPP;
protected int alphaProtected(){
return 1;
}
private int alphaPrivate(){
return 1;
}
}
package pack2;
import pack1.Alpha;
public class AlphaSub extends Alpha{
int alphasubPP;
private int alphasubPrivate;
protected int alphasubProtected;
public int alphasubPublic;
public void meth() throws CloneNotSupportedException{
new AlphaSub().alphaProtected(); //OK
new Gamma().alphaProtected(); /*COMPILE ERROR. */
}
}
很明显,即使 AlphaSub 和 Gamma 都从 Alpha
继承了 alphaProtected()
,也不能调用 Gamma 从 AlphaSub 继承的 alphaProtected()
。 .
如果这种情况是一个类的 protected 方法只能从该类内部调用,则不会调用 clone
[由 Object
类的每个类继承]另一个类不可能吗??
有人可以澄清一下吗?
最佳答案
JLS 6.6.2.1. 中涵盖了您所经历的内容:
6.6.2.1. Access to a protected Member
Let C be the class in which a protected member is declared. Access is permitted only within the body of a subclass S of C.
In addition, if Id denotes an instance field or instance method, then:
If the access is by a qualified name Q.Id or a method reference expression Q :: Id (§15.13), where Q is an ExpressionName, then the access is permitted if and only if the type of the expression Q is S or a subclass of S.
If the access is by a field access expression E.Id, or a method invocation expression E.Id(...), or a method reference expression E :: Id, where E is a Primary expression (§15.8), then the access is permitted if and only if the type of E is S or a subclass of S.
If the access is by a method reference expression T :: Id, where T is a ReferenceType, then the access is permitted if and only if the type T is S or a subclass of S.
你是对的,如果你用 new Gamma().clone();
替换 new Gamma().alphaProtected();
,你会得到同样的编译错误。
关于java - 谁能解释一下这里发生了什么 : "protected" modifier in java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28565464/