Inherit method with unrelated return types

吃可爱长大的小学妹 提交于 2019-12-05 13:21:36
Matthias

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

As a workaround, you can create an adapter class.

Edwin Dalorzo

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!