NullPointerException:覆盖Derived类中的Base类的构造函数调用方法 [英] NullPointerException : Overriding constructor calling method of Base class in Derived class

查看:142
本文介绍了NullPointerException:覆盖Derived类中的Base类的构造函数调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

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();
    }
}

执行代码时我得到了一个异常:

On executing the code I got an exception:

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)

我无法理解为什么有 NullPointerException 和异常的 stackTrace 。任何人都可以帮助我理解?

I'm unable to understand why there is NullPointerException and the stackTrace of the exception. Anyone could help me to understand?

您可以在此处查看代码。

推荐答案

new Derived()创建派生 object,这意味着首先调用它的超类构造函数,然后调用方法 - 但是你已经覆盖方法所以它是被调用的那个方法的子版本。在该方法中,您调用 bar.length 尚未初始化。

new Derived() creates a Derived object, which implies calling its super class constructor first, which in turn calls method - but you have overriden method so it is the child version of that method which is called. In that method, you call bar.length which has not been initialised yet.

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

Conclusion: it is almost never a good idea to call an overridable method in a constructor.

这篇关于NullPointerException:覆盖Derived类中的Base类的构造函数调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆