9

I have for example an Interface A and B. A has an (abstract) method called foo. B extends A.

It is possible to override foo in the interface B even with @Override, but is there any situation where that makes sense? There is nothing to override, because both methods have to be abstract and have no body. So I guess there is no situation where this makes sense, right?

So why is it possible to override in an interface?

ashiquzzaman33
  • 5,781
  • 5
  • 31
  • 42
stonar96
  • 1,359
  • 2
  • 11
  • 39

2 Answers2

11

One situation is when you want to update the Javadoc documentation to reflect a more specific contract in the method in the subinterface, as is the case with Collection#addAll(Collection) and List#addAll(Collection):

  • Collection#addAll(Collection):

    Adds all of the elements in the specified collection to this collection (optional operation)...

  • List#addAll(Collection:

    Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator (optional operation)...

A subinterface can also add a default implementation starting Java 8.

M A
  • 71,713
  • 13
  • 134
  • 174
8

A subtype can impose more conditions, change the return type, change throw types. One example

interface AutoCloseable
    void close() throws Exception

interface Closeable extends AutoCloseable
    void close() throws IOException

(A subtype may also override with an erased version of the method signature... but that's old story)

In java8, sub-interface can provide a default impl for the abstract method

interface DummyCloseable extends Closeable
{
    default void close()
    {
        // do nothing
    }
ZhongYu
  • 19,446
  • 5
  • 33
  • 61
  • What about type parameters? Can anything fun happen with those? – Erick G. Hagstrom Sep 25 '15 at 19:23
  • That makes sense, you mean a Covariant Return Type like that example http://stackoverflow.com/questions/14694852/can-overridden-methods-differ-in-return-type – stonar96 Sep 25 '15 at 19:26
  • I guess, barring erausre, they need "same" type parameters - http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.2 – ZhongYu Sep 25 '15 at 19:26
  • @stonar96 - yes, return/throw types of the sub-interface must be "compatible" with the super-interface :) – ZhongYu Sep 25 '15 at 19:27
  • Thank you for your answer, I have never heard about Covariant Return Type before. That's really interesting. – stonar96 Sep 25 '15 at 19:29