Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Methods with the same signature but different return type in two interfaces

Tags:

java

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() ?

like image 710
Spn Avatar asked Sep 08 '18 19:09

Spn


1 Answers

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 Strings are also Objects, 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).

like image 122
Andy Turner Avatar answered Oct 12 '22 22:10

Andy Turner