我正在尝试从父类重写toString
方法,但每当我尝试运行该程序时,即使我的构造函数已经初始化,它也会抛出NullPointerException
。扩展Car
的{{1}}类就是问题所在。我删除程序运行的Vehicle
。
以下是我的课程:
车辆:
spec.getNoOfDoors
汽车:
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);
}
}
这是错误:
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..
}
}
答案 0 :(得分:3)
我认为错误观念是
zero
以某种方式与
相同(或覆盖)IndexOutOfBoundsException
在超类(CarSpec spec;
)中声明和初始化。但是,这是not the case。
这两个不同的属性,您只能访问子类中VehicleSpec spec;
类型的Vehicle
。这个spec
不会被初始化,只是因为你已经在你的超类中初始化了CarSpec
。
所以你需要在子类的构造函数中初始化这个spec
,如
VehicleSpec spec
请注意,此行为隐藏而非覆盖。与方法不同,变量在编译时而不是在运行时解析。
答案 1 :(得分:0)
试试这个
public class Car extends Vehicle{
//Below 'spec' is local for Car and not have the reference Vehicle class 'spec'
CarSpec spec;
public Car(CarSpec spec, String serialNo, double price, int size) {
super(serialNo, price, size, spec);
//Local 'spec' assigned by the spec received from constructor and the same in Vehicle
this.spec = spec;
}
@Override
public String toString() {
return String.format(super.toString() + "Door: %d", spec.getNoOfDoors()); //<- this is where the problem is..
}