Home > Mobile >  How to override abstract generic method with concrete return type?
How to override abstract generic method with concrete return type?

Time:09-29

How do I create an abstract method that is generic, but is implemented to return a concrete type?

Consider this simple abstract class:

public abstract class Master {

    public abstract <T> T getValue();

}

Each of the subclasses of Master should implement the getValue() method, but return a concrete type:

public class DateSlave extends Master {

    @Override
    public LocalDate getValue() {

        return LocalDate.now();
    }
}

Or:

public class ListSlave extends Master {

    @Override
    public List<String> getValue() {

        return new ArrayList<String>();
    }
}

I assume I am doing the whole generics thing wrong as I'm not very well-versed in their usage. The above subclasses offer this warning: Unchecked overriding: return type requires unchecked conversion. Found 'java.util.List<java.lang.String>', required 'T'.

Is there a better way to create an abstract method that the subclasses must implement, while also providing their own concrete return type?

CodePudding user response:

This is what you are looking for:

public abstract class Master<T> {

    public abstract T getValue();

}

public class DateSlave extends Master<LocalDate> {

    @Override
    public LocalDate getValue() {

        return LocalDate.now();
    }
}

public class ListSlave extends Master<List<String>> {

    @Override
    public List<String> getValue() {

        return new ArrayList<String>();
    }
}

Master<T> is a generic class. The return type is declared on each concrete class.

  • Related