Different return types of abstract method in java without casting

erwingun2010 picture erwingun2010 · Feb 23, 2013 · Viewed 21.5k times · Source

I am trying to implement and override a method with different return types without being forced to cast the return type.

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
}

My question: Is it possible to return different types without being forced to cast? How has the abstract method look like to solve the problem?

I think there has to be a solution because the compiler should know the return type...

Answer

Perception picture Perception · Feb 23, 2013

In your example, classes C and D will not compile. The overridden methods in them violate the Liskov substitution principle, aka, their return type is incompatible with their parent class. What you are looking to do can be accomplished with generics, as long as you are willing to forego the use of primitives as your return type.

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) { }
}