Inherit method with unrelated return types

I have the following code snippet

public class Test { static interface I1 { I1 m(); } static interface I2 { I2 m(); } static interface I12 extends I1,I2 { I12 m(); } public static void main(String [] args) throws Exception { } } 

When I try to compile it, I got an error.

 Test.java:12: types Test.I2 and Test.I1 are incompatible; both define m(), but with unrelated return types. 

How to avoid this?

+4
source share
4 answers

As discussed in Java - calling a method name in an interface implementation , you cannot do this.

As a workaround, you can create an adapter class.

+2
source

There is only one case where this will work, as mentioned by xamde , but not fully explained. This is due to covariant return types .

In JDK 5, the covariant returns to where it is added, and as such is a valid case that will compile and run without problems.

 public interface A { public CharSequence asText(); } public interface B { public String asText(); } public class C implements A, B { @Override public String asText() { return "C"; } } 

Therefore, the following will execute without errors and print "C" on the main output:

 A a = new C(); System.out.println(a.asText()); 

This works because String is a subtype of CharSequence.

+1
source
+1
source

I had the same issue and it seems to be good using Oracle's JDK 7.

0
source

Source: https://habr.com/ru/post/1401398/


All Articles