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?
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.
You can not. If class X implements interface Y, then it must implement all methods/properties defined by it.
you can override a default method of an interface from the implementing class.
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With