java.util.ArrayList<car> cList = new java.util.ArrayList<Car>();
car[] cArray = new car[20];
假设我有一个丰田类,它扩展了汽车类。 Car 类有一个打印方法,该方法在 Toyota 类中被重写。
我知道如果我创建 Toyota 对象然后将它们放入 cArray 中,它们将成为 Car 对象,如果我想在它们上调用 print(Toyota t)
函数,我需要将print() 方法调用中的对象如下所示:(这是向上转型还是向下转型?)
假设 cArray 的前 10 个索引中有 Toyota 对象
Toyota toy = (Toyota)cArray[0];
toy.print(toy); //this should call the Toyota's print method
如果我使用 ArrayList,这可能吗?
Toyota toy = (Toyota)cList.get(0);
toy.print(toy); //does this call Toyota's print method or car's print method?
最后一点:我不确定 toy.print(toy) 是否是解决此问题的正确方法,我已经阅读了教科书和 javadoc 等,但我还没有之前见过使用过object.method(exactSameObject)。在我的 Main 中,我需要调用它,我使用 Car.print(toy) ,但是编译器声明不能从静态上下文中引用它。显然我不理解一些基本概念,请帮忙!
最佳答案
Toyota toy = (Toyota)cArray[0];
toy.print(toy); //this should call the Toyota's print method
确实,这会调用丰田的打印方法,但是,这真的是您想要的吗?
如果您重写丰田中的 toString() 方法,则可以执行以下操作:
System.out.println( toy );
重写的方法看起来像这样:
public String toString() {
return "I'm a Toyota!";
}
现在不需要转换。
关于java - 在 Array 与 ArrayList 中转换对象并调用该对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19458903/