title: Override compareTo() method in custom Java class?
body: <p>I have both a Dog and Cat class which look something like this:</p>
  
  <pre><code>public class Dog implements Speakable
  {
  private String name;
  
  public Dog(String name)
  {
      this.name = name;
  }
  
  public void speak()
  {
      System.out.println("Woof! Woof!");
  }
  
  public String toString()
  {
      return "Dog: " + name;
  }
  
  }
  </code></pre>
  
  <p>These classes both implement an interface I have created called Speakable which looks like this:</p>
  
  <pre><code>public interface Speakable
  {
    public void speak();
  }
  </code></pre>
  
  <p>This Speakable interface exists because I need a reference variable that allows me to add Dogs and Cats to the same ArrayList and still invoke the speak() method on them.</p>
  
  <p>I also need to override the compareTo() method of the Comparable interface so I can compare the names of dogs. When calling this method, I think my code will look like this: a.compareTo(b). I want this new method to return -1 if a is greater than b, 1 if a is less than b, and 0 if they are equal. </p>
  
  <p>I think I need the Dog class to specifically implement Comparable in addition to Speakable so the Comparable interface I have written is this:</p>
  
  <pre><code>public interface Comparable&lt;Dog&gt;
  {
      public int compareTo(Object obj);
  }
  </code></pre>
  
  <p>How do I override the compareTo() method to meet the needs I listed above? I know I will need several if statements, but I can't think of a way to write this without calling the compareTo() method within the new compareTo() method. Is that legal? Shouldn't the compareTo() method from the comparable interface already contain these decisions?</p>