`
yuyeyi
  • 浏览: 36583 次
  • 性别: Icon_minigender_1
  • 来自: 湖南
社区版块
存档分类
最新评论

做一个饲养员给动物喂食物的例子体现JAVA中的面向对象思

阅读更多
interface Animal { 
    public void eat(Food food); 
} 
/** 
*@authorleno 
*一种动物类:猫 
*/ 
class Cat implements Animal { 
    public void eat(Food food) { 
      System.out.println("小猫吃"+food.getName()); 
    } 
} 
/** 
*@authorleno 
*一种动物类:狗 
*/ 
class Dog implements Animal { 
    public void eat(Food food) { 
      System.out.println("小狗啃"+food.getName()); 
    } 
} 

/** 
*@authorleno 
*食物抽象类 
*/ 
abstract class Food { 
    protected String name; 
    public String getName() { 
      return name; 
    } 

    public void setName(String name) { 
      this.name = name; 
    } 
} 

/** 
*@authorleno 
*一种食物类:鱼 
*/ 
class Fish extends Food { 
    public Fish(String name) { 
      this.name = name; 
    } 
} 
/** 
*@authorleno 
*一种食物类:骨头 
*/ 
class Bone extends Food {  
    public Bone(String name) { 
      this.name = name; 
    } 
} 

/** 
*@authorleno 
*饲养员类 
* 
*/ 
class Feeder { 
    /** 
    *饲养员给某种动物喂某种食物 
    *@paramanimal 
    *@paramfood 
    */ 
    public void feed(Animal animal,Food food) { 
      animal.eat(food); 
    } 
} 

/** 
*@authorleno 
*测试饲养员给动物喂食物 
*/ 
public class TestFeeder { 

    public static void main(String[] args) { 
      Feeder feeder=new Feeder(); 
      Animal animal=new Dog(); 
      Food food=new Bone("肉骨头"); 
      feeder.feed(animal,food); //给狗喂肉骨头 
      animal=new Cat(); 
      food=new Fish("鱼"); 
      feeder.feed(animal,food); //给猫喂鱼 


    } 
} 
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics