6

I was looking at Map and SortedMap documentation from Java 7 and I have realized that SortedMap, which extends Map overrides entrySet(), keySet() and values().

AFAIK, interfaces cannot implement a method in Java prior to Java 8. So what was the reason for overriding these methods?

6

It looks as though the methods were overridden solely so that different documentation could be provided.

For all three methods, the only difference in documentation is that the SortedMap version adds "The set's iterator returns the entries in ascending key order." to the main description and "sorted in ascending key order" to the return value description.


P.S. The obvious follow-up question is why weren't these three method signatures simply changed to return SortedSet instead of Set. Unfortunately I can't come up with a reason for this, as the Java language seems to allow this sort of change, and the additional methods on SortedSet seem trivial to implement.

  • 3
    returning SortedSet was not allowed when this interface was introduced. SortedMap javadoc says it's there since Java 1.2 while covariant returns were introduced only in Java 1.5 – gnat Apr 9 '16 at 14:52
  • If it is for the purpose of documentation (a reasonable guess), it's funny that it makes part of the docs more confusing: the "Methods inherited from interface..." section just seems wrong. This is particularly true with List -- most of the methods inherited from Collection are "overridden". – Hawkeye Parker Oct 6 '16 at 0:46
2

From the Java Language Spec for Java 7:

About all that can be accomplished by an overriding method declaration, other than to affirm a method signature, is to refine the return type or to restrict the exceptions that might be thrown by an implementation of the method.

So: You can change the throws signature, and/or you can specify a more specific sub-type of the original return type. For example:

interface Foo {
  Foo get() throws IOException;
}

interface Bar extends Foo {
  Bar get() throws RuntimeException;
}

Is completely legal, as would be omitting the throws clause completely for either one.

0

I don't think that there is any such thing as interface methods being able to "override" parent interface methods (in Java 7); only (sub) classes can have "override" methods. SortedMap and Map are interfaces not classes. Therefore, what you're seeing is merely a documentation issue, rather than some technical issue.

(And overloading by sub-interfaces is another story, though the methods you're citing are not overloads as they have the same signature.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.