为什么受保护的方法可以在不相关的类中访问?
我用 Eclipse ide 编写了以下代码:
public interface X
{
final public static int SOME_CONST = 0;
}
public class Handle implements X
{
protected void methodHandle () { }
//...
}
public class User implements X
{
Handle handle = new Handle();
private void methodUser ()
{
Y y = new Y() // anonymous inner class
{
public void methodY ()
{
handle.methodHandle (); // <--- why this is NOT giving error ?
}
}
}
}
即使 Handle.methodHandle ()
是 protected
,它仍然可以从匿名内部 类的内部方法调用
代码>方法?为什么会这样,我错过了什么吗? Handle
和 User
之间的唯一关系是它们实现
相同的X
。
I have below code written with Eclipse ide:
public interface X
{
final public static int SOME_CONST = 0;
}
public class Handle implements X
{
protected void methodHandle () { }
//...
}
public class User implements X
{
Handle handle = new Handle();
private void methodUser ()
{
Y y = new Y() // anonymous inner class
{
public void methodY ()
{
handle.methodHandle (); // <--- why this is NOT giving error ?
}
}
}
}
Even though Handle.methodHandle ()
is protected
, it's still callable from the inner method of an anonymous inner class
method ? Why is it happening, am I missing something ? The only relation between Handle
and User
is that they are implement
ing same X
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果两个类都在同一个包中,则可以调用受保护的方法。
有关更多详细信息,请参阅此。
If both classes are in the same package, the protected method can be called.
See this for more details.
如果调用类位于同一个包中,它将能够调用受保护的方法。如果这不是您想要的,您应该将您的方法设为私有。
If the calling class is in the same package, it is going to be able to call protected methods. If that's not what you wanted, you should make your methods private.
同一包中的类并非“不相关”。
Classes in the same package are not 'unrelated'.