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;
The NullPointerException can be avoided using checks and preventive techniques like the following: Making sure an object is initialized properly by adding a null check before referencing its methods or properties. Using Apache Commons StringUtils for String operations e.g. using StringUtils.
Java NullPointerException (NPE) is an unchecked exception and extends RuntimeException .
It is generally a bad practice to catch NullPointerException.
NullPointerException is thrown when an application attempts to use an object reference that has the null value. These include: Calling an instance method on the object referred by a null reference. Accessing or modifying an instance field of the object referred by a null reference.
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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With