【问题标题】:Reach parent class methods from arraylist of subclasses从子类的arraylist到达父类方法
【发布时间】: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,而不是 ArrayList?为什么你发布伪代码而不是实际代码?如果表达式是 Object 类型(如 allInOne.get(0) 是),则您只能访问 Object 的方法。如果您的列表是 List 而不是 List,则表达式 allInOne.get(0) 将是 Car 类型,您将可以访问 Car 方法。

标签: java object inheritance arraylist multiple-inheritance


【解决方案1】:

使用ArrayList&lt;Car&gt;代替对象列表

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

那么你可以访问所有这些方法:

allInOne.get(0).getBrand();

如果你出于某种原因想坚持Object 列表,那么你可以这样做:

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

【讨论】:

  • 我将 ArrayList 更改为 ,现在我可以联系到他们了。但是当我尝试达到汽车变量“x”时,我想我将不得不 if (allInOne.get(a).getClass() == Automobile.class) { Automobile into = (Automobile) allInOne.get(一种); System.out.println("x= " + into.getX()); }
  • @Greeed 任何时候你必须使用getClass()instanceof,你通常会错误地建模你的类。在这种情况下,无需执行任何操作;只需使用Car into
  • @Greeed 因为你在AutomobileBus 中没有任何额外的方法,所以除非你在这些类中有不同的方法,否则不需要显式转换它们,如果你需要的话使用@chrylis 提到的instanceof
【解决方案2】:

在实例化列表时,将 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. 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 2012-04-19
    • 2012-02-22
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    相关资源
    最近更新 更多