Comparable Interface

Objects that have an ordering are compared using the compareTo() method.

21. Monster Object



Monster Object

Say that you are writing a computer game that involves a hero who encounters various monsters. Monsters have several characteristics: hit pointsstrengthage, and name. The number of hit points a monster has is how far it is from death. A monster with a large number of hit points is hard to kill. The hero also has hit points.

When the hit points of the hero reach zero, the game is over. The strength of a monster affects how many hit points the hero looses when the monster hits the hero. The age and name of the monster do not affect the outcome of battles between the monster and a hero.

Monster needs a compareTo() method so that monsters can be compared. For example, the game will present the hero with monsters in increasing order of difficulty.

Here is an outline of the Monster class.

class Monster implements 
  private int hitPoints, strength, age;
  private String name;
  public Monster( int hp, int str, int age, String nm )
    hitPoints = hp; strength = str; this.age = age; name = nm;
  public int getHitPoints() { return hitPoints; }
  public int getStrength()  { return strength; }
  public int getAge() { return age; }
  public String getName() { return name; }
  public String toString() 
    return "HP: " + getHitPoints() + " \tStr: " + getStrength() + "\t" + getName();
  public int compareTo(  )
     .... more goes here ...

Question 21:

Fill in the blanks.