Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 669
stonar96 Avatar asked Sep 25 '15 19:09

stonar96


People also ask

Should you override interface methods?

If you have default method in an interface, it is not mandatory to override (provide body) it in the classes that are already implementing this interface. In short, you can access the default methods of an interface using the objects of the implementing classes.

Can interface override a method of another interface?

You can not. If class X implements interface Y, then it must implement all methods/properties defined by it.

Can we override default method of interface?

you can override a default method of an interface from the implementing class.

Can we override an interface method with visibility that is not public?

No. We cannot override an interface method if it's visibility is not public. And if it has its visibility as public then you can override it with the same method signature (i.e., with the same access specifier public) whenever you implement the interface to any class.


2 Answers

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.

like image 158
M A Avatar answered Oct 21 '22 16:10

M A


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
    }
like image 29
ZhongYu Avatar answered Oct 21 '22 15:10

ZhongYu