基于我的一个较早的问题 Link我正在努力学习更多关于 Casting 和 Instanceof 的知识。这是基于 HeadFirst 书中描述的场景
所以基本上我现在有一个新类 (Hybrid),它继承 self 的 Vehicle 类,我想做的是转换一个 Hybrid Object 来显示作为混合体的额外信息。它符合要求,但并没有真正让我知道是什么导致了错误,除了它只是在我标记的那一行结束。
public class ShowroomDriver {
public static void main(String[] args) {
Showroom cars = new Showroom("Cars");
Hybrid hybrid1 = new Hybrid("Toyota Prius", "Focus", "John Smith", "TOTAP453453987346283",
getCalendar(2,3,1998), getCalendar(24,2,2012),
"Right Hand",//Hybrid Only Info Edit: Forgot to commentout
true,
'C',
650, 82.0); //Cost & (Hybrid MPG)
cars.addVechicle(hybrid1);
cars.getVechicles();
混合类
import java.util.Calendar;
public class Hybrid extends Vehicle{
private double consumption;
private String drive;
public Hybrid(String Manufacture, String Model, String CustomerName, String Vin,
Calendar DateManufactured, Calendar Datesold, String Drive,
boolean HasbeenSold,
char TaxBand,
double Cost, double Consumption){
super(Manufacture, Model, CustomerName, Vin, DateManufactured, Datesold,
HasbeenSold,
TaxBand,
Cost);
this.consumption = Consumption;
this.drive = Drive;
}
public Double getConsumption() { return this.consumption; }
public String getDrive() { return this.drive; }
}
新载具方法
public void displayDetails(){
for(int i = 0; i <cars.theVehicles.size(); i++){
if(this.cars.theVehicles.get(i) instanceof Hybrid){//Error here
Hybrid thehybrids = (Hybrid)this.cars.theVehicles.get(i);
System.out.println("Consumption: " + thehybrids.getConsumption()+ "\n" +
"Drive: " + thehybrids.getDrive());
}
}
}
最佳答案
你需要施法吗?您已经覆盖了 displayDetails() 方法来显示特定于混合动力的信息。因此,您应该能够调用它,运行时将确定要调用的正确方法。
关于java - Instanceof 和 Casting,多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13331191/