When does a rabbit have eight legs? When there are two of them.
/**
* A WildAnimal "is-a" Animal -- this means that a WildAnimal has the behavior we described in Animal!
*/
/**
* Extends means we must write code for all of the methods
* we defined in Animal. If we don't, we won't be able to create
* a WildAnimal!
*/
public class WildAnimal extends Animal{
/**
* What additional state might a WildAnimal have?
* In addition to the name, color, hungerLevel, and favoriteFood,
* a WildAnimal has a predator, an environment, and a strength!
*/
private WildAnimal predator;
private String environment;
private int strength;
/**
* super refers to the constructor in the "parent" class --
* this would be the constructor we made in Animal!
* That constructor needs a color, name, and favoriteFood to
* work properly, so we use super to send it the information
* it needs to finish making a WildAnimal!
*/
public WildAnimal(String color, String name, String favoriteFood, WildAnimal predator, String environment){
super(color, name, favoriteFood);
/**
* This WildAnimal "has-a" wild animal too! This means the WildAnimal
* we are creating has another WildAnimal defined as part of it's state.
* One of the traits of the WildAnimal is its predator, which is also
* a WildAnimal.
*/
this.predator = predator;
this.environment = environment;
strength = (int) (Math.random() * ((10 - 1) + 1));
}
/**
* A WildAnimal already has all of the behavior defined in Animal.
* Below is the additional behavior that a WildAnimal would have, but
* wouldn't make sense for EVERY animal to have!
*/
public String getEnvironment(){
return environment;
}
public WildAnimal getPredator(){
return predator;
}
public int getStrength(){
return strength;
}
public void battlePredator(){
System.out.println(predator.getName() + " confronts " + getName() + "!");
if(strength > predator.strength){
System.out.println(getName() + " beats " + predator.getName() + "!");
strength += 1;
if(predator.strength > 0){
predator.strength -= 1;
}
else{
System.out.println("Resetting " + predator.getName() + "'s strength.");
predator.strength = 5;
}
}
else if(strength < predator.strength){
System.out.println(predator.getName() + " beats " + getName() + "!");
if(strength > 0){
strength -= 1;
}
else{
System.out.println("Resetting " + getName() + "'s strength.");
strength = 5;
}
predator.strength += 1;
}
else{
System.out.println("They tie!");
}
}
/**
* Because WildAnimal extends Animal, we must define the move() method if
* we want to be able to create a WildAnimal.
* extends means that a WildAnimal "is-a" Animal!
*/
public void move(){
System.out.println(getName() + " is free-range!");
}
}