在循环遍历父类列表时,是否有比使用 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]

提问人:AnonymousThankfulPerson 提问时间:11/12/2023 更新时间:11/12/2023 访问量:21

问:

我的问题与很久以前发布的问题非常相似:在循环遍历其父类 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() 方法,因此它会运行错误而不会像我那样强制转换它)。有没有办法在没有所有这些重复代码的情况下做同样的事情?特别是如果我有更多的课程,我认为这会很长。

Java 多态性

评论

2赞 Jens 11/12/2023
父类不应知道有关子类的任何信息。所以你的方法是错误的。您应该调用在子类中实现的抽象方法
0赞 Hovercraft Full Of Eels 11/12/2023
您可以使用“访客设计模式”来模拟双重调度,但是是的,最好的答案是按照上面@Jens的评论:改进您的OOP设计,这样就没有必要了。
0赞 Reinderien 11/12/2023
做一些类似 pastebin.com/JLsQ6sTZ 的事情 - 不要将你的谓词表示为否定词,而是表示为正数。
0赞 AnonymousThankfulPerson 11/13/2023
谢谢你的评论。问题是我想使用的方法不适用于所有子类。就像 canSurviveOutOfWater 放在子类 cat 中没有意义一样,我只想把它放在实现接口 WaterDweller 的类中,所以我不应该把它放在父类 animal 中,对吧?
0赞 Jens 11/14/2023
是的,你是对的。

答: 暂无答案