NullPointerException:覆盖派生类中基类的构造函数调用方法 [英] NullPointerException : Overriding constructor calling method of Base class in Derived class
问题描述
我有这个代码片段:
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()
创建一个 Derived
对象,这意味着首先调用其超类构造函数,即反过来调用 method
- 但是你已经覆盖了 method
所以它是被调用的方法的子版本.在该方法中,您调用尚未初始化的 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:覆盖派生类中基类的构造函数调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!