The example will be shown on Comparable
, but the question is about all similar situations.
So Comparable is a generic Interface:
public interface Comparable<T>
We can implement it in two ways (mainly):
Implement with a generic type and override
compareTo
method with known-type parameter:MyClass implements Comparable<MyClass> { @Override public int compareTo(MyClass o) { return myVar.compareTo(o.myVar) } }
Implement with no generic type and use compareTo with
Object
parameter:MyClass implements Comparable { @Override public int compareTo(Object o) { return myVar.compareTo(((MyClass)o).myVar) } }
Which approach is more acceptable? What are the pros and cons of each other? I guess that the first approach is better, as there is no additional casting, but is this the only advantage?