java – 帮助理解受保护方法的问题

我正在阅读Sybex Complete Java 2认证学习指南2005年4月(ISBN0782144195).本书适用于想要通过java认证的java开发人员.

在关于访问修饰符(以及其他修饰符)的章节之后,我发现了以下问题(#17):

True or false: If class Y extends
class X, the two classes are in
different packages, and class X has a
protected method called abby(), then
any instance of Y may call the abby()
method of any other instance of Y.

这个问题让我有点困惑.

据我所知,你可以在同一个类(或子类)的任何变量上调用protected方法.您不能在变量上调用它,层次结构中的变量比您更高(例如,您实现的接口).

例如,您不能仅仅因为继承它而克隆任何对象.

但问题没有提到变量类型,只涉及实例类型.

我有点困惑,回答“真实”.

书中的答案是

False. An object that inherits a protected method from a superclass in a different package may call that method on itself but not on other instances of the same class.

这里没有关于变量类型的内容,只有实例类型.

这很奇怪,我不明白.

谁能解释一下这里发生了什么?

解决方法:

True or false: If class Y extends class X, the two classes are in different packages, and class X has a protected method called abby(), then any instance of Y may call the abby() method of any other instance of Y.

“False. An object that inherits a protected method from a superclass in a different package may call that method on itself but not on other instances of the same class”.

让我们把它写下来,就像BalusC那样,并向Y添加一个调用Y的任何其他实例的abby()的方法:

package one;
public class X {
    protected void abby() {
    }
}

package other;
import one.X;
public class Y extends X {
    public void callAbbyOf(Y anyOther) {
        anyOther.abby();
    }
}

Y可以调用它具有引用的Y的任何实例的abby()方法.所以书中的答案显然是错误的. Java没有特定于实例的范围(与例如具有实例私有范围的Scala不同).

如果我们试图变得仁慈,也许这个问题意味着说“Y的任何其他实例”,它可以访问碰巧在内存中的任何Y实例的方法 – 这是不可能的,因为Java没有直接的内存访问.但在这种情况下,问题的措辞非常糟糕,您甚至可以回答:“错误.您不能在不同JVM上的实例上调用方法,或者在垃圾收集的实例上调用方法,或者JVM上的实例不能调用方法一年前等“

上一篇:java.lang.SecurityException:签名者信息与同一包中其他类的签名者信息不匹配


下一篇:java – J2ME Midlet – 自签名证书