I have two interfaces :
interface S {
public String m1();
}
interface O {
public Object m1();
}
I decide to implement both O and S in a class Test :
class Test implements O, S {
}
My question :
Why must I only implement the method public String m1()
and not the other ?
And secondly, why can't I implement public Object m1()
instead of public String m1()
?
Java allows you to use covariant return types for overriding methods.
This means that an overriding method can return a subtype of the type declared on the overridden method.
In this case, String
is covariant with Object
; since all String
s are also Object
s, it is a suitable return type for implementing O.m1()
and O.m2()
.
But you can't have two methods with the same signature in a single class (return type isn't part of the signature). So you can only implement at most 1, when the return types are compatible, as here. (And if they are not compatible, you'd get a compiler error).
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