飼育員として動物に餌を与える例としてJAVAの中の対象思

1941 ワード


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); //     


    } 
}