我正在阅读 Sybex Complete Java 2 Certification Study Guide 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 方法。您不能在层次结构比您更高的变量上调用它(例如,您实现的接口(interface))。
例如,您不能仅仅因为继承了任何对象就克隆它。
但是这些问题没有提到变量类型,只提到了实例类型。
我有点困惑,回答"is"。
书上的答案是
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 那样有一个实例私有(private)的范围)。
如果我们尝试仁慈一点,也许这个问题的意思是说“Y 的任何 其他实例”,它可以访问恰好在内存中的 Y 的任何实例的方法 - 这是不可能的,因为 Java 没有直接内存访问。但是在那种情况下,这个问题的措辞太糟糕了,你甚至可以回答:“错了。你不能调用不同 JVM 上的实例的方法,或者已经被垃圾收集的实例,或者 JVM 上死亡的实例一年前等等。”
关于java - 帮助理解 protected 方法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2244611/