多態的問題
public class Demo {
? ? public static void main(String[] args){
? ? ? ? Master ma = new Master();
? ? ? ? ma.feed(new Animal(), new Food());
? ? ? ? ma.feed(new Cat(), new Bone());
? ? ? ? ma.feed(new Dog(), new Fish());
? ? }
}
class Animal{
? ? public void eat(Food f){
? ? ? ? System.out.println("我是一個小動物,正在吃" + f.getFood());
? ? }
}
class Cat extends Animal{
? ? public void eat(Food f){
? ? ? ? System.out.println("我是一只小貓咪,正在吃" + f.getFood());
? ? }
}
class Dog extends Animal{
? ? public void eat(Food f){
? ? ? ? System.out.println("我是一只狗狗,正在吃" + f.getFood());
? ? }
}
class Food{
? ? public String getFood(){
? ? ? ? return "事物";
? ? }
}
class Fish extends Food{
? ? public String getFood(){
? ? ? ? return "魚";
? ? }
}
class Bone extends Food{
? ? public String getFood(){
? ? ? ? return "骨頭";
? ? }
}
class Master{
? ? public void feed(Animal an, Food f){
? ? ? ? an.eat(f);
? ? }
}
2016-07-24
Cat,Dog繼承于Animal,可以使用Animal類型的變量來引用Cat和Dog的對象,Food類似。以ma.feed(new Cat(), new Bone());為例,feed(Animal an, Food f),an是Animal類型的變量,引用了Cat的對象,即可以使用Cat對象中所有從Animal繼承的方法,而an實際引用的是Cat而不是Animal,所以調用方法時調用的就是Cat中的方法。Food的情況類似。
2016-07-20
有誰能解釋一下怎么實現的