练习4:实现多态的两种方式 使用父类作为方法形参和返回值实现多态 使用多态实现主人领养三只宠物并喂养宠物的过程。 (1)创建包net.hnjdzy.unit07.exercise04; (2)在此包下定义抽象类Animal,有一个抽象方法eat(); (3)定义Dog类、Cat类和Bird类继承Animal抽象类,实现eat()抽象方法; (4)定义主人类Master,有一个领养宠物的方法Animal getAnimal(int typeId),一个喂养宠物的方法void feed(Animal an); (5)定义测试类Test04实现主人领养和喂养宠物。
时间: 2024-03-02 08:50:16 浏览: 373
Animal.java:
```java
package net.hnjdzy.unit07.exercise04;
public abstract class Animal {
public abstract void eat();
}
```
Dog.java:
```java
package net.hnjdzy.unit07.exercise04;
public class Dog extends Animal {
@Override
public void eat() {
System.out.println("狗吃骨头");
}
}
```
Cat.java:
```java
package net.hnjdzy.unit07.exercise04;
public class Cat extends Animal {
@Override
public void eat() {
System.out.println("猫吃鱼");
}
}
```
Bird.java:
```java
package net.hnjdzy.unit07.exercise04;
public class Bird extends Animal {
@Override
public void eat() {
System.out.println("鸟吃虫子");
}
}
```
Master.java:
```java
package net.hnjdzy.unit07.exercise04;
public class Master {
public Animal getAnimal(int typeId) {
Animal animal = null;
switch (typeId) {
case 1:
animal = new Dog();
break;
case 2:
animal = new Cat();
break;
case 3:
animal = new Bird();
break;
default:
break;
}
return animal;
}
public void feed(Animal an) {
an.eat();
}
}
```
Test04.java:
```java
package net.hnjdzy.unit07.exercise04;
public class Test04 {
public static void main(String[] args) {
Master master = new Master();
Animal animal1 = master.getAnimal(1);
Animal animal2 = master.getAnimal(2);
Animal animal3 = master.getAnimal(3);
master.feed(animal1);
master.feed(animal2);
master.feed(animal3);
}
}
```
阅读全文