1.多态的实现 (1)定义一个抽象类Animal,包含一个抽象方法eat0。 (2)定义三个具体的动物类:Bird、Fish、Cat,它们都继承Animal类,并实现eat0方法。 (3)定义一个接口Pet,包含两个方法:play0和getName()。 (4)在Cat类中实现IPet接口,并实现play0方法和getName()方法。 (5)编写一个测试类,在主函数中,创建一个数组,将其中的元素分别指向Bird、Fish、Cat对象,并通过循环调用eat0方法和play0方法。要求程序能够正确输出每种动物的eat0方法和只有Cat对象的play0方法。
时间: 2024-03-19 15:46:09 浏览: 123
好的,下面是实现多态的代码:
Animal.java:
```
public abstract class Animal {
public abstract void eat0();
}
```
Bird.java:
```
public class Bird extends Animal {
@Override
public void eat0() {
System.out.println("Bird is eating.");
}
}
```
Fish.java:
```
public class Fish extends Animal {
@Override
public void eat0() {
System.out.println("Fish is eating.");
}
}
```
Cat.java:
```
public class Cat extends Animal implements IPet {
@Override
public void eat0() {
System.out.println("Cat is eating.");
}
@Override
public void play0() {
System.out.println("Cat is playing.");
}
@Override
public String getName() {
return "Cat";
}
}
```
IPet.java:
```
public interface IPet {
void play0();
String getName();
}
```
Test.java:
```
public class Test {
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();
}
if (animals[2] instanceof IPet) {
IPet pet = (IPet) animals[2];
pet.play0();
}
}
}
```
输出结果:
```
Bird is eating.
Fish is eating.
Cat is eating.
Cat is playing.
```
阅读全文