In implementing the comparable interface for a class, are we overriding the compareTo method?
If yes, who originally has defined the compareTo method that we are overriding it?
My guess is that we are not overriding in the sense that there was no other implementation before that we are overriding it but only add @override because we are implementing an interface. Anyway today I was asked about this specifically, and wasn't sure.
Asked
Active
Viewed 212 times
1

apadana
- 13,456
- 15
- 82
- 98
-
1The [`Comparable`](http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html) interface defines the contract you are required to implement, which includes the `compareTo` method. The `@Override` annotation is a compile time check to make sure that you intentions (of the method you think you're overriding) meets reality (with what can be overridden). For example, if your accidentally call the method `compareto`, you'll get two errors, one for not meeting the contractual requirements of the interface and one because the compiler can't find the named method in the class hierarchy – MadProgrammer Jul 10 '15 at 01:51
-
You question is not clear! Do you want to know who designed the API ? Or what the usage of @override? – Harry.Chen Jul 10 '15 at 01:52
-
By adding @override, are we overriding a default implementation of compareTo? Was there such a default implementation in Object (parent) class? – apadana Jul 10 '15 at 02:11
-
No. Using the @Override annotation is somewhat optional (though recommended). What really matters is your method's implementation. – tonychow0929 Jul 10 '15 at 02:13
1 Answers
2
Your guess is correct, the @Override
annotation can either mean that you're intending to override a method from a superclass, or that you are intending to implement a method from an interface.
And it's logical to be a bit surprised by this usage of the @Override
annotation. It would probably have been clearer for the reader if there was an @Implement
annotation to indicate that you intended to implement an interface method.
But then there would be confusion about overriding an abstract method from a superclass; which annotation should you use in that case. To keep things simple, there is only one annotation for this purpose: @Override
.

Erwin Bolwidt
- 30,799
- 15
- 56
- 79