不明白一下代码的 for (car car : carForRent) 为什么是 car car : carForRent
不明白一下代码的 for (car car : carForRent) 为什么是 car car : carForRent
car [ ] carForRent={new passengerCar(1,"奥迪A4",500,4),new passengerCar(2,"马自达6",400,4),
new pickUp(3,"皮卡雪6",450,4,2),new passengerCar(4," 金龙 ",800,20),
new trunk(5,"松花江",400,4),new trunk(6,"依维柯",1000,20)};
System.out.println("序号"+"\t"+"汽车名称"+"\t"+"租金"+"\t"+"\t"+"容量");
//打印输出可供租的汽车清单
for (car car : carForRent) {
//用instanceOf来测试左边类型的对象是否是右边类型的实例,返回值为Boolean
if(car instanceof passengerCar){
//若它是客车类型的实例,则打印出客车应该有的属性值,这里注意强转,否则不会出现
//passengerCar类的CarCapacity属性
System.out.println(car.getCarNumber()+"\t"+car.getCarName()+"\t"+car.getCarRentMoney()
+"/天"+"\t"+"载人:"+((passengerCar)car).getCarCapacity()+"人");
}
if(car instanceof pickUp){
System.out.println(car.getCarNumber()+"\t"+car.getCarName()+"\t"+car.getCarRentMoney()
+"/天"+"\t"+"载人:"+((pickUp)car).getCarCapacity()+"人"+"\t"
+"载货:"+((pickUp)car).getCarCarryCargo()+"吨");
}
if(car instanceof trunk){
System.out.println(car.getCarNumber()+"\t"+car.getCarName()+"\t"+car.getCarRentMoney()
+"/天"+"\t"+"载货:"+((trunk)car).getCarCarryCargo()+"吨");
}
}