基于我的Link的一个较早的问题,我正在研究有关Casting和Instanceof的更多信息。这是基于HeadFirst书中描述的场景
因此,基本上,我现在有了一个新类(Hybrid),该类从我的Vehicle类继承,我想要做的是将Hybrid对象转换为混合对象,以显示混合对象带来的额外信息。它符合要求,但实际上并没有让我知道导致错误的原因,只是它仅在我标记的行结束。
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()方法来显示特定于混合的信息。因此,您应该只能调用此方法,运行时将确定正确的调用方法。