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.


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部