从不同包的另一个实例的子类调用受保护的方法

2023-05-05Java开发问题
3

本文介绍了从不同包的另一个实例的子类调用受保护的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我想从提供此受保护方法的类的子类中调用另一个实例的受保护方法.请参阅以下示例:

I want to invoke a protected method of another instance from within a subclass of the class providing this protected method. See the following example:

public class Nano {

    protected void computeSize() {
    }

}

public class NanoContainer extends Nano {

    protected ArrayList<Nano> children;

}

public class SomeOtherNode extends NanoContainer {

    // {Nano} Overrides

    protected void computeSize() {
        for (Nano child: children) {
            child.computeSize();            // << computeSize() has protected access in nanolay.Nano
        }
    }

}

javac 告诉我 computeSize() 在 Nano 中具有受保护的访问权限.我看不出这是什么原因(我以为我已经在其他代码中这样做了).我想保持这种方法受到保护,我该怎么办?

javac tells me that computeSize() has protected access in Nano. I can't see the reason for this (I thought I was already doing this in some other code). I'd like to keep this method being protected, what can I do?

javac version "1.7.0_09"

编辑

我想提供一个精简的版本,但我没有想到这些类位于不同的包中.

Edit

I wanted to provide a stripped down version, but I didn't think about the fact, that the classes lie in different packages.

nanolay.Node
nanolay.NanoContainer
nanogui.SomeOtherNode

推荐答案

您可以通过子类化和覆盖来访问受保护的方法;当它们在同一个包中可用时.我会补充一些细节.您可以在此处阅读详细信息.

You could access the protected methods either by subclassing and overriding; also when they are available in the same package. I will add some details. You can read details here.

您的示例位于 java 中 Object 类中可用的 protected clone() 方法的行上;您不能直接在任何对象上调用它(尽管所有对象都隐式地从 Object 类扩展).

The example that you have is on lines of the protected clone() method available in the Object class in java; you cannot directly call it on any object (although all object implicitly extend from the Object class).

这篇关于从不同包的另一个实例的子类调用受保护的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

如何使用 JAVA 向 COM PORT 发送数据?
How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)...
2024-08-25 Java开发问题
21

如何使报表页面方向更改为“rtl"?
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)...
2024-08-25 Java开发问题
19

在 Eclipse 项目中使用西里尔文 .properties 文件
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)...
2024-08-25 Java开发问题
18

有没有办法在 Java 中检测 RTL 语言?
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)...
2024-08-25 Java开发问题
11

如何在 Java 中从 DB 加载资源包消息?
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)...
2024-08-25 Java开发问题
13

如何更改 Java 中的默认语言环境设置以使其保持一致?
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)...
2024-08-25 Java开发问题
13