提问人:AnonymousThankfulPerson 提问时间:11/12/2023 更新时间:11/12/2023 访问量:21
在循环遍历父类列表时,是否有比使用 instanceof 更好的方法来访问子类方法?[复制]
Is there a better way to access a child class method when looping through a list of the parent class than using instanceof? [duplicate]
问:
我的问题与很久以前发布的问题非常相似:在循环遍历其父类 java 时获取一个子类,但是,在应用给定的解决方案时,我觉得必须有一种更有效的方法。有人在帖子的评论中也提出了这个建议,但我真的无法理解他们给出的解决方案。他们只是声称使用多态性,但我看不出这如何适用于这种情况。
System.out.println("\n\n***** Here are the animals that can dwell in water, along with whether they can also live on land. (4 animals printed)");
for(Animal animal : animalList) {
if(animal instanceof WaterDweller)
{
System.out.print(animal);
if(animal instanceof Whale)
{
Whale temp = (Whale) animal;
if(temp.canLiveOutOfWater())
{
System.out.println("\t Can live out of water");
}
else
{
System.out.println("\t Can't live out of water");
}
}
if(animal instanceof Fish)
{
Fish temp = (Fish) animal;
if(temp.canLiveOutOfWater())
{
System.out.println("\t Can live out of water");
}
else
{
System.out.println("\t Can't live out of water");
}
}
if(animal instanceof Otter)
{
Otter temp = (Otter) animal;
if(temp.canLiveOutOfWater())
{
System.out.println("\t Can live out of water");
}
else
{
System.out.println("\t Can't live out of water");
}
}
if(animal instanceof Turtle)
{
Turtle temp = (Turtle) animal;
if(temp.canLiveOutOfWater())
{
System.out.println("\t Can live out of water");
}
else
{
System.out.println("\t Can't live out of water");
}
}
}
}
从本质上讲,canLiveOutOfWater() 是一种适用于鲸鱼和鱼等类的方法,但不适用于它们的父类动物。我想在遍历动物的 arrayList 时使用这些方法(其中一些根本没有 canLiveOutOfWater() 方法,因此它会运行错误而不会像我那样强制转换它)。有没有办法在没有所有这些重复代码的情况下做同样的事情?特别是如果我有更多的课程,我认为这会很长。
答: 暂无答案
评论