目前处于刚开始学习Java,所以对于面向对象里面的多态很是头疼。实在是搞不懂,很想放弃。但是一定要坚持下去,还是多做题,然后就算跟着抄代码,也要多写多观察。
下面是我在抄了代码之后,在网上找的练习题。因为只有要求,没有答案,作为第一个自己写出来的题目。所以发布出来!
题目要求:
假设动物园某管理员(Master类)每天需要给他所负责饲养的狮子(Lion),猴子(Monkey),鸟(Bird)喂食,用一个程序模拟喂食过程。
要求:
饲养员喂动物时,不同的动物执行吃的功能
三种不同动物吃的东西不同。狮子吃肉,猴子吃香蕉,鸟吃米
使用接口实现喂养不同动物的多态。
因为狮子、猴子和鸟都属于动物,所以可以创建一个动物类。我选择创建一个动物的接口:
public interface Animal {
void eat();
}
创建狮子(Lion)类,并实现Animal接口:
public class Lion implements Animal{
@Override
public void eat() {
System.out.println("狮子吃肉!");
}
}
创建猴子(Monkey)类,实现接口:
public class Monkey implements Animal{
@Override
public void eat() {
System.out.println("猴子吃香蕉!");
}
}
创建鸟(Bird)类,实现接口:
public class Bird implements Animal{
@Override
public void eat() {
System.out.println("鸟吃虫子!");
}
}
创建动物园管理员(Master类):
public class Master {
public void feedAnimal(Animal animal){
animal.eat();
}
}
创建测试类(Test)类:
public class Test {
public static void main(String[] args) {
// 建一个管理员
Master master = new Master();
// 多态,向上转型
// 多态,一步一步实现每个动物的喂养
// Animal animal = new Lion();
// animal.eat();
// Animal animal1 = new Monkey();
// animal1.eat();
// Animal animal2 = new Bird();
// animal2.eat();
// 本题目中要求有三种动物,所以可以创建一个长度为3的数组,用来存放。
Animal[] animals = {new Lion(),new Monkey(),new Bird()};
// animals[0].eat();
// 数组遍历,并实现动物的喂养
for (int i = 0; i < animals.length; i++) {
animals[i].eat();
}
}
}