I made this code and i’m trying to create different classes that extends Ability but return different values and it keep giving me error on type of each class.
private static final List<AbstractAbility<?>> LIST = new ArrayList<>();
public static void main(final String[] args)
{
LIST.add(new Bargain<>());
LIST.add(new BargainBoolean<>());
for (final var ability : LIST)
{
System.out.println(ability.getClass().getSimpleName() + " -> " + ability.getValue());
}
}
private static class Bargain<Double> extends AbstractAbility<Double>
{
@Override
public double getValue()
{
return 0.166;
}
}
private static class BargainBoolean<Boolean> extends AbstractAbility<Boolean>
{
@Override
public boolean getValue()
{
return false;
}
}
private static abstract class AbstractAbility<T>
{
public abstract T getValue();
}
>Solution :
There are two problems with your code.
First, this means something else than you think it means:
private static class Bargain<Double> extends AbstractAbility<Double>
You are creating a class Bargain here with a type parameter confusingly named Double. It’s like writing this:
private static class Bargain<U> extends AbstractAbility<U>
You don’t want class Bargain to have a type parameter; you just want it to extend class AbstractAbility with a type argument Double:
private static class Bargain extends AbstractAbility<Double>
Second: In class Bargain, your getValue() method should return a value of the correct type. Not the primitive type double:
public double getValue()
But the wrapper type Double:
public Double getValue()
Because that’s what’s specified in the superclass.
The same, of course, for class BargainBoolean.