5、创建学生类
package net.YGQ.p03.t03;
public class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void feed(Animal animal) {
if (animal instanceof Cat) {
System.out.println(name + "喂养猫咪[" + animal.getName() + "]。");
} else if (animal instanceof Dog) {
System.out.println(name + "喂养狗崽[" + animal.getName() + "]。");
} else if (animal instanceof Bird) {
System.out.println(name + "喂养鸟儿[" + animal.getName() + "]。");
} else {
System.out.println(name + "喂养动物[" + animal.getName() + "]。");
}
animal.speak();
animal.move();
animal.eat();
}
}
6、创建测试学生类
package net.YGQ.p03.t03;
public class TestStudent {
public static void main(String[] args) {
Student student = new Student();
student.setName("张三丰");
Animal animal1 = new Cat();
animal1.setName("虎丸");
animal1.setAge(4);
Animal animal2 = new Dog();
animal2.setName("瑞瑞");
animal2.setAge(5);
Animal animal3 = new Bird();
animal3.setName("豆豆");
animal3.setAge(3);
student.feed(animal1);
student.feed(animal2);
student.feed(animal3);
}
}