受保护成员范围
我正在为 SCJP 做准备,我还知道受保护的成员范围位于包内以及其他包中,并且具有某些条件,例如只有继承才可能。
例如 : 我有三个类作为 Parentclass Childclass Friendclass
package x.parent;
class Parentclass{
protected int x=10;
...............
}
package x.child;
class Childlass extends Parentclass{
super.x=20;
...............
}
package x.child;
import x.parent.Parentclass;
class Friendclass{
Parentclass pc = new Parentclass();
pc.x=30;
...............
}
背后的原因是什么,在 Friendclass 中,成员 x 不会接受为其分配值,在 Childclass 的情况下表现为私有成员。
Iam preparing for SCJP , also i came to know that protected members scope is within the package as well as in other package with some conditions like possible only with inheritance.
For example :
i have three classes as Parentclass Childclass Friendclass
package x.parent;
class Parentclass{
protected int x=10;
...............
}
package x.child;
class Childlass extends Parentclass{
super.x=20;
...............
}
package x.child;
import x.parent.Parentclass;
class Friendclass{
Parentclass pc = new Parentclass();
pc.x=30;
...............
}
Whats the reason behind that, in Friendclass the member x will not accept to assign a value to that, behaves as private member not in case of Childclass.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有四个访问修饰符
由于它使用默认修饰符,因此如果满足以下条件之一,则它具有访问权限:
因此它会失败标准,因此您无权访问。
There are four access modifiers
Since it uses the default modifier, it has access if one of the following is true:
So it fails the criteria, and so you don't get access.
您甚至无法访问
Childclass
中的Parentclass.x
,因为x
具有默认可见性(不受保护)。请参阅 http://download.oracle.com/javase/tutorial/java/ javaOO/accesscontrol.html编辑:
x.child.Friendclass
与x.parent.Parentclass
不在同一个包中。x.child.Friendclass
不继承自x.parent.Parentclass
。正如 TotalFrickinRockstarFromMars 的摘要所述和 Java 访问控制文档也指出的那样,这意味着
Friendclass
不允许访问字段x
。You can't even access
Parentclass.x
inChildclass
becausex
has default visibility (not protected). See http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.htmledit:
x.child.Friendclass
is not in the same package asx.parent.Parentclass
.x.child.Friendclass
does not inherit fromx.parent.Parentclass
.as TotalFrickinRockstarFromMars's summary states and the Java access control docs also state, this means that
Friendclass
is not allowed to access the fieldx
.