从子 class 的数组列表中获取父 class 方法
Reach parent class methods from arraylist of subclasses
我正在尝试从我的对象 Automobile()、Bus() 的 main() 中的 ArrayList 访问我的父 class Car() 变量和方法,它们都继承 Car()。它让我有机会获得 .Class 并且我知道我可以比较 class 是 Automobile 还是 Bus 然后做一些操作,但我实际上是在尝试对 allInOne() ArrayList 进行排序getModel() 字符串。
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;
}
在实例化 List 时,将 Car 更改为引用类型而不是 Object,这样您就可以使用从 Parent Class.
继承的 methods/attributes
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.
不使用对象列表 ArrayList<Car>
ArrayList<Car> allInOne = new ArrayList<>();
那么您可以访问所有这些方法:
allInOne.get(0).getBrand();
或
如果出于某种原因你想坚持 Object
的列表,那么你可以这样做:
((Car) allInOne.get(0)).getBrand();
我正在尝试从我的对象 Automobile()、Bus() 的 main() 中的 ArrayList 访问我的父 class Car() 变量和方法,它们都继承 Car()。它让我有机会获得 .Class 并且我知道我可以比较 class 是 Automobile 还是 Bus 然后做一些操作,但我实际上是在尝试对 allInOne() ArrayList 进行排序getModel() 字符串。
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;
}
在实例化 List 时,将 Car 更改为引用类型而不是 Object,这样您就可以使用从 Parent Class.
继承的 methods/attributesArrayList<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.
不使用对象列表 ArrayList<Car>
ArrayList<Car> allInOne = new ArrayList<>();
那么您可以访问所有这些方法:
allInOne.get(0).getBrand();
或
如果出于某种原因你想坚持 Object
的列表,那么你可以这样做:
((Car) allInOne.get(0)).getBrand();