【发布时间】:2020-07-27 14:58:23
【问题描述】:
我知道如何从ArrayList 获取随机元素,但我不知道如何也只显示 1 个元素的方法。例如,我有两个子类,其中包含一些非常基本的方法(它们基本上只是打印一些东西),ArrayList 在超类中。
这是我的代码,其中 Cat 和 Dog 是子类。现在代码打印其中一个,但显示两个类的方法。例如,如果程序选择 Dog,那么我只想显示 Dog 的 noise() 和 furr() 的结果。我怎么能这样做?
ArrayList<Animal> an = new ArrayList<>();
an.add(new Cat());
an.add(new Dog());
for (Animal a : an) {
a.noise();
a.furr();
}
int randomIndex = (int) (Math.random() * an.size());
System.out.println( "The animal: " + an.get( randomIndex ));
【问题讨论】:
-
这样做你打破了 oop 的基础之一:多态性。当您将元素放入列表时,您应该将所有项目视为动物。你的动物类或接口应该足够丰富以便有用,以便可以使用 Animal 方法调用它们。例如,Animal.noise() 将在 Cat 和 Dog 中被覆盖以发出不同的声音。也许 Animal.skin() 会被狗、猫和鹦鹉覆盖。