java lang保_java.lang.Object的受保护方法如何保护子类?
如果您引用它的表達式的編譯時類型是您自己的類或子類,則只能訪問不同包中類型的受保護成員. (其中“你的”類是包含代碼的類.)你自己的類必須是原來聲明方法的類的子類.
這是一個例子假設Base與所有其他類在不同的包中:
package first;
public class Base
{
protected void Foo() {}
}
// Yes, each class is really in its own file normally - but treat
// all the classes below as being in package "second"
package second;
public class Child extends Base
{
public void OtherMethod(Object x)
{
((Base) x).Foo(); // Invalid: Base is not Child or subclass
((Child) x).Foo(); // Valid: Child is Child
((GrandChild) x).Foo(); // Valid: GrandChild is subclass of Child
((OtherChild) x).Foo(); // Invalid: OtherChild is not Child or subclass
}
}
public class GrandChild extends Child {}
public class OtherChild extends Base {}
換句話說,它允許您訪問“像你一樣的對象”的受保護成員.
A protected member or constructor of
an object may be accessed from outside
the package in which it is declared
only by code that is responsible for
the implementation of that object.
6.6.2.1 Access to a protected Member
Let C be the class in which a
protected member m 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, 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, where E is a Primary
expression, or by a method invocation
expression E.Id(. . .), where E is a
Primary expression, then the access is
permitted if and only if the type of E
is S or a subclass of S.
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的java lang保_java.lang.Object的受保护方法如何保护子类?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java环境变量设置xp_java环境变
- 下一篇: centos 对已有卷扩容_centos