gpt4 book ai didi

java - 重写 - 降低方法作为私有(private)方法的可见性, eclipse 错误

转载 作者:行者123 更新时间:2023-11-30 03:09:20 25 4
gpt4 key购买 nike

public class First {
public void methodOne() {
System.out.println("in Parent methodOne");
}

public void methodTwo() {
System.out.println("in Parent methodTwo");
}
}

public class Second extends First{
private void methodOne() {
System.out.println("methodOne");
}

@Override
public void methodTwo() {
System.out.println("methodTwo");
}

public static void main(String[] args) {
First first = new Second();
first.methodOne();
}
}

在第二个类中,我们有一个私有(private)方法“methodOne”。这在 Eclipse 中显示错误“无法降低从 First 继承的方法的可见性”。我知道这个错误是因为重写方法不应降低可见性

尽管它显示了编译错误,但它执行得很好,并给出了 in Parent methodOne 的输出。如果是编译错误,为什么会产生输出?

当我将访问说明符更改为 protected 时,它会在控制台中给出预期的编译错误!

最佳答案

  • Eclipse 按照 Java 语言规范 (JLS) 实现了自己的编译器,称为 Eclipse Compiler for Java (ECJ)。
  • 即使存在编译错误,该编译器也可以创建CLASS 文件。但是,在出现严重错误的情况下(例如,引用不一致的二进制文件,很可能与无效的构建路径有关),Java 构建器不会生成任何 CLASS 文件。

如果您检查 Class Second使用decompilermethodOne将如下

          private void methodOne()
{
throw new Error("Unresolved compilation problem: \n\tCannot reduce the visibility of the inherited method from First\n");
}

由于引用是父类的并且方法是可见的,因此父方法被调用。

Eclipse 编译器识别出 methodOne 是父级的重写方法,并且应该遵循重写方法规则。

Java builder concepts -Eclipse

关于java - 重写 - 降低方法作为私有(private)方法的可见性, eclipse 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33951319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com