当我偶然发现这个问题时,我正在做一份学校作业单。我有这样的车辆类别:
public class Vehicle {
private static int idcouter = 0;
private int id;
private Condition condition;
private int price;
public Vehicle() {
this.id = idcouter++;
this.condition = condition;
this.price = price;
}
public Condition getCondition() {
return condition;
}
public void setCondition(Condition condition) {
this.condition = condition;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}}
还有卡车:
public class Truck extends Vehicle {
private boolean trailer;
public Truck() {
super();
this.trailer = trailer;
}
@Override
public void setPrice(int price) {
if (this.getCondition() == enums.Enums.Condition.NEW) {
if (this.trailer) {
int tempPrice = (int) (price * 0.95f);
super.setPrice(tempPrice);
} else {
super.setPrice(price);
}
} else {
int tempPrice = (int) (price * 0.85f);
super.setPrice(tempPrice);
}
}}
鉴于我的主要:
Truck t1 = new Truck();
Truck t2 = new Truck();
Truck t3 = new Truck();
t1.setPrice(200);
t2.setPrice(200);
t3.setPrice(200);
t1.setCondition(enums.Enums.Condition.NEW);
t1.setTrailer(true);
t2.setCondition(enums.Enums.Condition.NEW);
t2.setTrailer(false);
t3.setCondition(enums.Enums.Condition.USED);
t3.setTrailer(true);
System.out.println("Price: " + t1.getPrice());
System.out.println("Price: " + t2.getPrice());
System.out.println("Price: " + t3.getPrice());
为什么我的输出是:
Price: 170
适用于所有卡车 1,2 和 3。
这没有任何意义,它应该覆盖它。我对汽车(车辆的一个子类)做了类似的事情,效果非常好。我尝试过不同的事情,但我无法理解发生了什么。如果有人可以分享一些信息或为我指出正确的方向,我将不胜感激。预先感谢。
这是因为对于
trailer
的所有实例(false
、Truck
、t1
),成员变量 t2
的值都是 t3
。方法 setPrice
在调用 setTrailer
之前调用。
setPrice
的逻辑始终将trailer
视为false
,这是原生boolean
的默认值。如果 trailer
的类型为 Boolean
,则 setPrice
方法将为 NullPointerExcpetion
的所有调用抛出 setPrice(200)
。
Truck
和Car
的构造函数中的赋值是无用的,因为构造函数没有可以分配给this.xxxxx
变量的参数。