创建一个数组,将其中的元素分别指向Bird、Fish、Cat对象,并通过循环调用eat0方法和play0方法。
时间: 2024-03-22 10:39:05 浏览: 103
好的,以下是创建数组并循环调用方法的示例代码:
```java
public class Animal {
public void eat0() {
System.out.println("Animal is eating.");
}
public void play0() {
System.out.println("Animal is playing.");
}
}
public class Bird extends Animal {
@Override
public void eat0() {
System.out.println("Bird is eating.");
}
@Override
public void play0() {
System.out.println("Bird is playing.");
}
}
public class Fish extends Animal {
@Override
public void eat0() {
System.out.println("Fish is eating.");
}
@Override
public void play0() {
System.out.println("Fish is playing.");
}
}
public class Cat extends Animal {
@Override
public void eat0() {
System.out.println("Cat is eating.");
}
@Override
public void play0() {
System.out.println("Cat is playing.");
}
}
public class Main {
public static void main(String[] args) {
Animal[] animals = new Animal[3];
animals[0] = new Bird();
animals[1] = new Fish();
animals[2] = new Cat();
for (Animal animal : animals) {
animal.eat0();
animal.play0();
}
}
}
```
输出结果如下:
```
Bird is eating.
Bird is playing.
Fish is eating.
Fish is playing.
Cat is eating.
Cat is playing.
```
需要注意的是,这里使用了 Animal 类作为父类,而 Bird、Fish、Cat 继承自 Animal。在循环中,使用了父类 Animal 的引用,但是运行时会根据实际对象的类型来调用相应的方法。这就是多态的应用。
阅读全文