我有以下代码片段:

class Base {
    public Base() {
        method();
    }

    void method() {
        System.out.println("In Base");
    }
}

class Derived extends Base {
    private String bar;

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

    public void method() {
        System.out.println(bar.length());
    }

    public static void main(String[] args) {
        Base base=new Derived();
        base.method();
    }
}


执行代码时出现异常:

Exception in thread "main" java.lang.NullPointerException
    at Derived.method(Main.java:22)
    at Base.<init>(Main.java:5)
    at Derived.<init>(Main.java:17)
    at Derived.main(Main.java:27)


我不明白为什么会有NullPointerExceptionstackTrace异常。有人可以帮助我理解吗?

您可以检查代码here

最佳答案

new Derived()创建一个Derived对象,这意味着首先调用其超类构造函数,该超类构造函数又调用method-但您已覆盖了method,因此它是该方法的子版本。在该方法中,您调用尚未初始化的bar.length

结论:在构造函数中调用可重写方法几乎从来不是一个好主意。

10-07 13:06
查看更多