gpt4 book ai didi

java - 为什么我没有被警告这个问题?

转载 作者:搜寻专家 更新时间:2023-11-01 04:03:45 24 4
gpt4 key购买 nike

假设我按以下方式定义了两个类:

public class A {

public A() {
foo();
}

public void foo() {
System.out.println("A");
}
}

public class B extends A {

private String bar;

public B() {
bar = "bar";
}

@Override
public void foo() {
System.out.println(bar);
}

}

然后我按以下方式实例化 B:

A test = new B();

那么为什么编译器和 IDE 不能分别警告我 B 的 foo 方法中会有一个 NullPointer?这不会很难检查,有时非常有用。

最佳答案

虽然这是一个设计错误,但它不是语法错误。

这里引用自 Effective Java 第 2 版第 17 项:继承的设计和文档,否则禁止:

There are a few more restrictions that a class must obey to allow inheritance. Constructors must not invoke overridable methods, directly or indirectly. If you violate this rule, program failure will result. The superclass constructor runs before the subclass constructor, so the overriding method in the subclass will be invoked before the subclass constructor has run. If the overriding method depends on any initialization performed by the subclass constructor, the method will not behave as expected.

一个听话的编译器会让它编译得很好,因为它在语言上是合法的。幸运的是,可以使用代码分析工具来发现这些设计错误,例如findbugs :

UR: Uninitialized read of field method called from constructor of superclass (UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR)

This method is invoked in the constructor of of the superclass. At this point, the fields of the class have not yet initialized.

关于java - 为什么我没有被警告这个问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2972336/

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