Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return any type using generic

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading