从子类的数组列表中访问父类方法



>我正在尝试从我的父类 Car(( 变量和方法访问我的父类 Car(( 变量和方法,从我的 ArrayList 在对象 Automobile((, Bus(( 中,它们都继承了 Car((。它让我有机会获得.类,我知道我可以比较类是汽车还是总线,然后执行一些操作,但我实际上正在尝试按 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<Car>

ArrayList<Car> allInOne = new ArrayList<>();

然后,您可以访问所有这些方法:

allInOne.get(0).getBrand();

或者如果您出于某种原因想坚持使用Object列表,那么您可以这样做:

((Car) allInOne.get(0)).getBrand();

实例化列表时,将 Car 更改为引用类型而不是 Object,以便可以使用从父类继承的方法/属性。

ArrayList<Car> allInOne = new ArrayList<Car>(); // Java 7    
ArrayList<Car> allInOne = new ArrayList<>(); // Java 8 it is not longer necessary to put reference type when instance an object. 

最新更新