Java NullPointerException when extending parent class

Viewed 6931

I'm getting NullPointerException whith below code.

Parent.java

public abstract class Parent {

    public Parent(){
        parentFunc();
    }

    public abstract void parentFunc();
}

Child.java

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

    @Override
    public void parentFunc() {
        list.add("First Item");
    }
}

when I create and instance of Child like new Child() I'm getting NullPointerException Here is my console output

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)

I know that exception occurs because of Child.parentFunc() which called in parent constructor, but I really got confused. So I wonder what is going on

What is the order of creation;

  1. When list variable is created
  2. When constructors are called
  3. When functions are created and called which called in constructors
4 Answers
Related