java - 帮助理解 protected 方法的问题

标签 java certificate access-modifiers protected

我正在阅读 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/

相关文章:

java - 如何使用 apache poi 将背景图像设置为居中

groovy - 特征中的私有(private)抽象声明给出静态上下文错误

java - 如何让用户停止java应用程序

java - 从 Java 访问继承自通用 Java 基类的 Scala 对象

c# - CertEnroll::CX509Enrollment::InstallResponse:找不到对象或属性。 0x80092004 (-2146885628)

windows - 代码签名服务之间有什么区别?

java - 为什么克隆可以在另一个对象上设置私有(private)字段?

c# - 仅将构造函数公开给基类,可能吗?

Java优化为游戏绘制背景图像

使用 iText 的 Java PDF 数字签名可见,但不可打印