Anthony Anthony - 1 year ago 49
Java Question

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

I'm trying to override a

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

Here are my classes:


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

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);


public class Car extends Vehicle{
CarSpec spec;

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

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(
at java.lang.String.valueOf(Unknown Source)
at Source)
at com.inventory.main.CarInventorySearch.main(

Answer Source

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.