I have both a Dog and Cat class which look something like this:
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;
}
}
These classes both implement an interface I have created called Speakable which looks like this:
public interface Speakable
{
public void speak();
}
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.
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.
I think I need the Dog class to specifically implement Comparable in addition to Speakable so the Comparable interface I have written is this:
public interface Comparable<Dog>
{
public int compareTo(Object obj);
}
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?