Does it make sense to override a method in an interface [duplicate]
Asked Answered
S

2

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?

Shiism answered 25/9, 2015 at 19:0 Comment(0)
H
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.

Helenahelene answered 25/9, 2015 at 19:1 Comment(4)
addAll() is a great example but perhaps you should show what the difference is in the contract.Hiphuggers
Yes. This is called a Covariant Return Type. See en.wikipedia.org/wiki/…Extinguisher
@ErickG.Hagstrom In my example both return void but the covariant return type feature still holds in general :)Helenahelene
Oops, yes, I see that now. :-)Extinguisher
E
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
    }
Elizaelizabet answered 25/9, 2015 at 19:12 Comment(5)
What about type parameters? Can anything fun happen with those?Extinguisher
That makes sense, you mean a Covariant Return Type like that example #14695352Shiism
I guess, barring erausre, they need "same" type parameters - docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.2Elizaelizabet
@Shiism - yes, return/throw types of the sub-interface must be "compatible" with the super-interface :)Elizaelizabet
Thank you for your answer, I have never heard about Covariant Return Type before. That's really interesting.Shiism

© 2022 - 2024 — McMap. All rights reserved.