不带强制转换的java中抽象方法的不同返回类型

erw*_*010 8 java methods return-type abstract

我试图实现和覆盖具有不同返回类型的方法,而不必强制转换返回类型.

public abstract class A {
public abstract Object getValue(String content);
}

public class B extends A {
public String getValue(String content) {...}
}

public class C extends A {
public int getValue(String content) {...}
}


public class D extends A {
public boolean getValue(String content) {...}
}

// Main loop:
for (A a : allAs)
{
// I want to use the method getValue() and corresponding to the type return a String, int or boolean without casting the return type
}
Run Code Online (Sandbox Code Playgroud)

我的问题:是否有可能返回不同类型而不被强迫演员?抽象方法如何解决问题?

我认为必须有一个解决方案,因为编译器应该知道返回类型......

Per*_*ion 16

在您的示例中,类CD不会编译.它们中被重写的方法违反了Liskov替换原则,也就是说,它们的返回类型与它们的父类不兼容.只要您愿意放弃使用原语作为返回类型,您可以使用泛型完成您要做的事情.

abstract class A<T> {
    public abstract T getValue(String content);
}

class B extends A<String> {
    public String getValue(String content) { }
}

class C extends A<Integer> {
    public Integer getValue(String content) { }
}

class D extends A<Boolean> {
    public Boolean getValue(String content) { }
}
Run Code Online (Sandbox Code Playgroud)