java - 尝试覆盖方法时奇怪的 Eclipse 行为

标签 java eclipse inheritance overriding

<分区>

我有这两个类,DogBeagle 扩展了 Dog

class Dog {
    protected String bark() {return "woof "; }
}
class Beagle extends Dog {
    private String bark() { return "arf "; }
}
class Test {
    public static void main(String args[]) {
        Dog[] dogs = {new Dog(), new Beagle()};
        for(Dog d : dogs)
            System.out.print(d.bark());
    }
}

当我使用任何其他编辑器而不是 Eclipse 时,上面的代码甚至无法编译。我收到此错误:

Attempting to assign weaker access privileges to bark() method in Beagle class.

您还可以看到此行为 here .

如果我使用 Eclipse Indigo(版本:3.7.2),这段代码可以正常编译,输出为:woof woof

请让我明白哪一个是正确的,为什么?

提前致谢!

最佳答案

If I use Eclipse, this code compiles fine and the output is: woof woof.

我不这么认为,你不能用树皮的方法来降低能见度

一定是

@Override
protected String bark() {
    return "arf ";
}

代替

@Override
private String bark() {
    return "arf ";
}

修改后,Begle 被正确覆盖了 bark 方法,因此输出必须是:

woof arf


边注:

Version: Neon.3 Release (4.6.3)

关于java - 尝试覆盖方法时奇怪的 Eclipse 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44676218/

相关文章:

java - JPA - InheritanceType.Joined 生成错误的表

JavaEE应用服务器还是轻量级容器?

java - 有异常的接口(interface)扩展无异常的接口(interface)

java - Elasticsearch 中的通配符搜索

java - 可以在静态方法中调用非静态方法吗?

java - 异常 java.lang.NoClassDefFoundError android/app/Activity

java - 在 Eclipse 中添加外部 .jar 文件

c# - 新继承的类在使用 EF Code First 迁移时重命名其属性名称

c++ - 不同类中的枚举不兼容?

Java连接池实现