when implements Comparable interface and override compareTo method,
@Override
public int compareTo(Name o) {
int val = this.name.compareTo(o.name);
if (val != 0) {
return val;
}
if (count != o.count) {
return count - o.count;
}
}
The third line, I realized that I can use compareTo when I override it, and it automatically compares things follows the natural order. But isn't compareTo an abstract method in the comparable interface. Without defining it, it still does compare? Also, why I do not need to use super keyword to distinguish this compareTo.
You are implementing the method
compareTo
in theclass Name extends Comparable<Name>
. This class has a member calledname
.If you were callingName.compareTo
in the third line, you would get a crash from infinity recursion, nor can you callComparable.compareTo
, which is abstract indeed.You are calling
X.compareTo
, where X is the type you declared the member variablename
with.In other words, this will only work if
name
is notinstanceof Name
.By the way, you will need to add an else branch with a return statement to your last if block, or this snippet won't compile.