假设我有一个存储泛型类型的集合,例如
public class MyCollection<T> {
public T getNext()
{
//Remove T from list
//Return T
}
}
我正在使用这个集合来存储子类型,例如
public class NormalPerson extends Human {
public void beNice() { }
}
public class Murderer extends Human {
public void kill() { }
}
...
MyCollection<Human> people = new MyCollection<>();
people.add(new NormalPerson());
people.add(new Murderer());
我想调用特定于每个子类型的方法。例如
Human person = people.getNext();
switch(person.getType()) {
case NORMAL:
person.beNice(); //Symbol not found
break;
case MURDERER:
person.kill(); //Symbol not found
break;
}
但是我不能,除非我投,例如
switch(people.getNext().getType()) {
case NORMAL:
NormalPerson person = (NormalPerson)people.getNext();
person.beNice();
break;
铸造是完成这项工作的唯一方法吗?我会以错误的方式解决这个问题吗?
谢谢