为什么我不能从 Java 中另一个包中的继承类调用受保护的方法?

2022-01-13 00:00:00 oop inheritance attributes java

假设有以下基类:

package bg.svetlin.ui.controls;

public abstract class Control {
    protected int getHeight() {
        //..
    }
    //...
}

另外,在同一个包中,有一个类继承:

Also, in the same package, there's a class that inherits:

package bg.svetlin.ui.controls;

public abstract class LayoutControl extends Control {
    public abstract void addControl(Control control);
    //...
}

那么,在另一个包中还有第三个类:

Then, there's a third class in another package:

package bg.svetlin.ui.controls.screen;

public abstract class Screen extends LayoutControl {
    //...
}

最后,还有实现类,同样在不同的包中:

And, finally, there's the implementation class, again in a different package:

package bg.svetlin.ui.controls.screen.list;    

public class List extends Screen {

    private final Vector controls = new Vector();

    public void addControl(Control control) {
        height += control.getHeight();
        controls.addElement(control);
    }
}

即使 List 继承自 Control,并且 getHeight()protected,还是会出现以下错误:

Even though List inherits from Control, and the getHeight() is protected, there's the following error:

getHeight() 在 bg.svetlin.ui.controls.Control 中具有受保护的访问权限

getHeight() has protected access in bg.svetlin.ui.controls.Control

我检查了我的导入是否正确.我正在使用 NetBeans.

I've checked that my imports are right. I'm using NetBeans.

知道有什么问题吗?我认为 protected 字段和方法对孩子来说是可见的,即使后者在不同的包中.

Any idea what's wrong? I thought protected fields and methods are visible to the children even if the latter are in a different package.

谢谢!

推荐答案

我认为受保护的字段和方法是对孩子可见,即使后者在不同的包中.

I thought protected fields and methods are visible to the children even if the latter are in a different package.

没错.类本身可以访问继承的受保护成员.但是,您试图在 some 控件参考上调用 getHeight 方法.您只能在 this 实例上调用它!

That's correct. The class itself has an access to the inherited protected members. But, what you're trying to do it to call the getHeight method on some Control reference. You're allowed to call it only on this instance!

为了更好地理解,让我引用 Kathy Sierra 的 SCJP 准备指南:

For a better understanding, let me quote Kathy Sierra's SCJP Preparation Guide:

但是对于包外的子类来说,这意味着什么访问超类(父)成员?这意味着子类继承该成员.然而,这并不意味着subclass-outside-the-package 可以使用引用访问成员到超类的一个实例.换句话说,受保护 =遗产.子类可以看到受保护的成员只能通过继承.

But what does it mean for a subclass-outside-the-package to have access to a superclass (parent) member? It means the subclass inherits the member. It does not, however, mean the subclass-outside-the-package can access the member using a reference to an instance of the superclass. In other words, protected = inheritance. The subclass can see the protected member only through inheritance.

相关文章