在继承关系中,一个多态的实例运用(动物园喂食系统)
多态:编译过程是一种情况,运行是另外一种情况。
当我们要用JAVA实现一个功能时,首先第一步要做的就是进行分析,这对于框架的构建十分关键。则一开始我们先定义我们需要的class:Zoo,ZooKeeper,Animal三大类。后面我们再按需求写具体的内容(Dog,Cat,etc)。下面是具体源码。
public class Zoo {
public static void main(String[] args) {
ZooKeeper zk = new ZooKeeper();
zk.feed(new Animal());
zk.feed(new Dog());
zk.feed(new Cat());
}
}
public class ZooKeeper {
public void feed(Animal animal){
animal.eat();
}
}
Zookeeper对于整个功能来说最为关键
public class Animal {
public void eat(){
System.out.println("Animals eat");
}
}
public class Dog extends Animal{
@Override
public void eat(){
System.out.println("The dogs eat the bone.");
}
}
public class Cat extends Animal{
@Override
public void eat(){
System.out.println("The cats eat fish.");
}
}
运行结果:
Animals eat.
The dogs eat the bone.
The cats eat fish.