Inherit method with unrelated return types

2019-05-04 20:49发布

问题:

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 error.

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

How to avoid this?

回答1:

As discussed in Java - Method name collision in interface implementation you can't do this.

As a workaround, you can create an adapter class.



回答2:

There is only one case in which this would work, which is mentioned by xamde, but not thoroughly explained. It's related to covariant return types.

In the JDK 5 the covariant returns where added, and as such the following is a valid case that would compile fine 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 run without errors and print "C" to the main output:

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

This works because String is a subtype of CharSequence.



回答3:

This is a bug in Sun's Java 6 compiler.



回答4:

I had the same problem and it seems to be fine by using the JDK 7 from Oracle.