【发布时间】:2020-01-04 11:05:50
【问题描述】:
我试图从我的 ArrayList 中的 Objects Automobile()、Bus() 中的所有继承 Car() 的 main() 中访问我的父类 Car() 变量和方法。它让我有机会获得 .Class,我知道我可以比较该类是汽车还是巴士,然后进行一些操作,但我实际上是在尝试通过 getModel() 字符串对 allInOne() ArrayList 进行排序。
public class Car {
private String brand;
private String model;
public String getBrand(){
return brand;
}
public String getModel(){
return model;
}
}
public class Automobile extends Car {
int x;
Automobile(String brand, String model, int x){
super(brand, model);
this.x = x;
}
}
public class Bus extends Car {
int x;
Bus(String brand, String model, int x){
super(brand, model);
this.x = x;
}
main(){
Car first = new Automobile("brand1", "model1", 2);
Car second = new Bus("brand2", "model2", 3);
ArrayList<Object> allInOne = new ArrayList<Object>();
allInOne.add(first);
allInOne.add(second);
//here is the question part
allInOne.get(0).getBrand;
}
【问题讨论】:
-
为什么要创建 ArrayList
标签: java object inheritance arraylist multiple-inheritance