Pau*_* E. 1 java collections polymorphism abstract-class
我是Java编程的初学者,想了解在这里处理多态引用的正确方法.
假设我们在C++中有以下(抽象)代码:
List<Fruit*> lstFruit;
...
// collect apples here
while (...)
{
Fruit* apple = new Apple("green");
lstFruits.append(apple);
}
...
lstFruit[i]->doSomething(); // here is our virtual method
Run Code Online (Sandbox Code Playgroud)
Java不允许我创建一个List包含对基类的引用的集合abstract.在这种情况下我该怎么办?我的目标是普遍使用不同的子类对象,无论他们的班级是什么.
您可以使用astract类创建一个泛型集合:
List<Fruit> l = new ArrayList<Fruit>();
l.add(new Apple());
l.get(0).someFunctionOnFruit();
Run Code Online (Sandbox Code Playgroud)