扩展父类时出现Java NullPointerException

Ism*_*hin 5 java inheritance

我得到的NullPointerException代码低于代码.

Parent.java

public abstract class Parent {

    public Parent(){
        parentFunc();
    }

    public abstract void parentFunc();
}
Run Code Online (Sandbox Code Playgroud)

Child.java

public class Child extends Parent {
    ArrayList<String> list = new ArrayList<String>();

    @Override
    public void parentFunc() {
        list.add("First Item");
    }
}
Run Code Online (Sandbox Code Playgroud)

当我创建和实例Childnew Child()我得到NullPointerException 这里是我的控制台输出

Exception in thread "main" java.lang.NullPointerException
    at Child.parentFunc(Child.java:8)
    at Parent.<init>(Parent.java:5)
    at Child.<init>(Child.java:3)
    at Main.main(Main.java:8)
Run Code Online (Sandbox Code Playgroud)

我知道因为在父构造函数中调用的Child.parentFunc()而发生异常,但我真的很困惑.所以我想知道发生了什么

什么是创造的顺序;

  1. 创建列表变量时
  2. 当构造函数被调用时
  3. 在函数创建和调用时,在构造函数中调用它们

Ama*_*ora 5

创建列表变量时?

一旦Child类的构造函数运行,它将被创建。

什么时候调用构造函数?

当您尝试使用new Child()构造对象时,会调用构造函数,Child并且会在内部调用super(),该调用超类构造函数Parent()。请注意,构造函数中的第一个语句Child()super()

系统将为您生成无参数的构造函数,如下所示:

public child()
{
 super();// calls Parent() constructor.
 //your constructor code after Parent constructor runs
}
Run Code Online (Sandbox Code Playgroud)

创建和调用函数时调用构造函数

弄清楚你想问什么。

Order Of Execution:
Run Code Online (Sandbox Code Playgroud)

父构造器->子构造器->列表