Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. public class Animal {
  2.    
  3.     private String name;
  4.     private double height;
  5.     private int weight;
  6.     private String favFood;
  7.     private double speed;
  8.     private String sound;
  9.    
  10.     // Instead of using an interface in a traditional way
  11.     // we use an instance variable that is a subclass
  12.     // of the Flys interface.
  13.    
  14.     // Animal doesn't care what flyingType does, it just
  15.     // knows the behavior is available to its subclasses
  16.    
  17.     // This is known as Composition : Instead of inheriting
  18.     // an ability through inheritance the class is composed
  19.     // with Objects with the right ability
  20.    
  21.     // Composition allows you to change the capabilities of
  22.     // objects at run time!
  23.    
  24.     public Flys flyingType;
  25.    
  26.     public void setName(String newName){ name = newName; }
  27.     public String getName(){ return name; }
  28.    
  29.     public void setHeight(double newHeight){ height = newHeight; }
  30.     public double getHeight(){ return height; }
  31.    
  32.     public void setWeight(int newWeight){
  33.         if (newWeight > 0){
  34.             weight = newWeight;
  35.         } else {
  36.             System.out.println("Weight must be bigger than 0");
  37.         }
  38.     }
  39.     public double getWeight(){ return weight; }
  40.    
  41.     public void setFavFood(String newFavFood){ favFood = newFavFood; }
  42.     public String getFavFood(){ return favFood; }
  43.    
  44.     public void setSpeed(double newSpeed){ speed = newSpeed; }
  45.     public double getSpeed(){ return speed; }
  46.    
  47.     public void setSound(String newSound){ sound = newSound; }
  48.     public String getSound(){ return sound; }
  49.    
  50.  
  51.     // Animal pushes off the responsibility for flying to flyingType
  52.    
  53.     public String tryToFly(){
  54.        
  55.         return flyingType.fly();
  56.        
  57.     }
  58.    
  59.     // If you want to be able to change the flyingType dynamically
  60.     // add the following method
  61.    
  62.     public void setFlyingAbility(Flys newFlyType){
  63.        
  64.         flyingType = newFlyType;
  65.        
  66.     }
  67.    
  68. }