//父类:车 属性:姓名
子类:汽车与货车 属性:载重量和载客量
创建一个Car数组存储A货车,B客车,C货车
A货车:载重1t B客车:载客50人 C货车:载重2t
打印数组
//父类:Car
class Car {
private String name;
public Car(String name){
this.name = name;
}
public String getName(){
return name;
}
}
//A货车
class Atruck extends Car {
String load;
public Atruck(String name,String load){
super(name);
this.load = load;
}
public String getLoad() {
return load;
}
}
//B客车
class Coach extends Car {
String zaike;
public Coach(String name,String zaike){
super(name);
this.zaike = zaike;
}
public String getZaike() {
return zaike;
}
}
//C货车
class Btruck extends Car {
String load;
public Btruck(String name,String load){
super(name);
this.load = load;
}
public String getLoad() {
return load;
}
}
//主函数
public class Text {
public static void main(String[] args) {
Car a = new Atruck("A货车","1吨");
Car b = new Coach("B客车","50人");
Car c = new Btruck("C货车","2吨");
Car[] arr ={a,b,c};
for (int i = 0; i < arr.length; i++) {
if (arr[i] instanceof Atruck) {
System.out.println("货车-名字:"+a.getName()+",载重量:"+((Atruck)a).getLoad());
}else if (arr[i] instanceof Coach) {
System.out.println("货车-名字:"+b.getName()+",载重量:"+((Coach)b).getZaike());
}else {
System.out.println("货车-名字:"+c.getName()+",载重量:"+((Btruck)c).getLoad());
}
}
}
}