Anthony Anthony - 21 days ago 7
Java Question

Method overriding another method is throwing NullPointerException even when constructor is already initialized

I'm trying to override a

toString
method from a parent class but whenever I try to run the program, it throws a
NullPointerException
even though my constructors are already initialized. The
Car
class that extends
Vehicle
is where the problem is. Ehen I remove the
spec.getNoOfDoors
the program runs.

Here are my classes:

Vehicle:

public abstract class Vehicle {
private String serialNo;
private Double price;
private Integer size;
VehicleSpec spec;

public Vehicle(String serialNo, double price, int size, VehicleSpec spec) {
this.serialNo = serialNo;
this.price = price;
this.size = size;
this.spec = spec;
}

... // getters and setters

@Override
public String toString() {
return String.format("%s - %s, Color: %s - Serial No.: %s - Price: %s - Size: %s - ", spec.getBrand(), spec.getModel(), spec.getColor(), this.serialNo, this.price, this.size);
}
}


Car:

public class Car extends Vehicle{
CarSpec spec;

public Car(CarSpec spec, String serialNo, double price, int size) {
super(serialNo, price, size, spec);
}

@Override
public String toString() {
return String.format(super.toString() + "Door: %d", spec.getNoOfDoors()); //<- this is where the problem is..
}
}


Here is the error:

Exception in thread "main" java.lang.NullPointerException
at com.inventory.main.Car.toString(Car.java:12)
at java.lang.String.valueOf(Unknown Source)
at java.io.PrintStream.println(Unknown Source)
at com.inventory.main.CarInventorySearch.main(CarInventorySearch.java:16)

Answer

I think the misconception is that the

CarSpec spec;

is somehow meant to be same (or override) the

VehicleSpec spec;

which is declared and initialized in the superclass (Vehicle). However, this is not the case.

These are two different properties, of which you will only be able to access the spec of type CarSpec in the subclass. This spec will not be initialized, just because you have initialized the VehicleSpec spec in your superclass.

So you need to initialize this spec in the constructor of the subclass like

this.spec = spec;

Note that this behaviour is hiding and not overriding. Variables, unlike methods, are resolved at compile-time and not at runtime.

Comments