简体   繁体   中英

How to override abstract generic method with concrete return type?

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' 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM