5

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
Matthias
  • 3,582
  • 2
  • 30
  • 41
Ismail Sahin
  • 2,640
  • 5
  • 31
  • 58
  • Parents are constructed first, then children. The List wasn't created when the function was called, hence the NPE. – duffymo Dec 20 '13 at 20:29

4 Answers4

5

When list variable is created?

It will be created once constructor of Child class runs.

When constructors are called?

When you try to make an object using new Child(), constructor is called for Child and it internally calls super() which calls the superclass constructor Parent().Note that the very first statement in Child() constructor is super().

The system will generate no-arguement constructor for you like this:

public child()
{
 super();// calls Parent() constructor.
 //your constructor code after Parent constructor runs
}

When functions are created and called which called in constructors

Clear out a bit what are you trying to ask .

Order Of Execution:

Parent Constructor->Child Constructor-->List

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Aman Arora
  • 1,232
  • 1
  • 10
  • 26
2

When parent constructor invoked the function called , You list not initialized and defailu value to the Object null is there,

 @Override
    public void parentFunc() {
        list.add("First Item");   // list not yet initialized
    }
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

You have an implicit Child() constructor. It calls Parent(), Parent() calls parentFunc() which is called in the sub-class. At that moment your list is still null and you get the NullPointerException (NPE).

See also:

Java Constructor and Field Initialization Order

Community
  • 1
  • 1
peter.petrov
  • 38,363
  • 16
  • 94
  • 159
2

It's usually a bad idea to call abstract methods from a constructor, as you exposed yourself to this kind of problem.

punx120
  • 124
  • 4