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)