public class TestAnimal { static void showPet(Animal a) { a.eat(); } // static void showCat(Homework7.Cat b){ // b.getName(); // b.play(); // } public static void main(String[] args){ Animal[] animal = new Animal[3]; animal[0] = new Bird(); animal[1] = new Fish(); animal[2] = new Cat(); Animal A = animal[0]; Animal B = animal[1]; Animal C = animal[2]; IPet cat = new Cat(); // // String[] dongwu = new String[3]; // dongwu[0] = A.toString(); // dongwu[1] = B.toString(); // dongwu[2] = C.toString(); // for(int i = 0;i<3;i++){ // System.out.println(); // } showPet(A); showPet(B); showPet(C); cat.play(); cat.getName(); } }我要将Bird、Fish、Cat对象对应数组元素,并用循环输出,要怎么改写
时间: 2024-03-25 16:38:29 浏览: 101
您可以将数组元素的类型改为 Animal,并使用 instanceof 运算符判断元素的类型,然后调用对应的方法。以下是修改后的代码:
```
public class TestAnimal {
static void showPet(Animal a) {
a.eat();
}
public static void main(String[] args){
Animal[] animals = new Animal[3];
animals[0] = new Bird();
animals[1] = new Fish();
animals[2] = new Cat();
IPet cat = new Cat();
for (int i = 0; i < animals.length; i++) {
if (animals[i] instanceof Bird) {
System.out.println("This is a bird:");
showPet(animals[i]);
} else if (animals[i] instanceof Fish) {
System.out.println("This is a fish:");
showPet(animals[i]);
} else if (animals[i] instanceof Cat) {
System.out.println("This is a cat:");
showPet(animals[i]);
cat.play();
cat.getName();
}
}
}
}
```
注意,为了调用 Cat 对象的 play() 和 getName() 方法,我们需要将 cat 对象的类型声明为 IPet,而不是 Animal。
阅读全文