微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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 2nd Edition,第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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐