Question

T is unrestricted in the following declaration.

abstract public class Defaults<T>

However, my Defaults class deals with only String, Integer, Double. Therefore, I would like to restrict T to String, Integer, Double.

Obviously, the following is not allowed as they are finals:

abstract public class Defaults<T extends String&Integer&Double>

How then can I do it?

Was it helpful?

Solution

You cannot. The closest thing you can do is give Defaults a private constructor

private Defaults() {}

...and provide factory methods only for the allowed classes:

public static Defaults<String> stringDefaults() { return new Defaults<>(); }
public static Defaults<Integer> integerDefaults() { return new Defaults<>(); }
public static Defaults<Double> doubleDefaults() { return new Defaults<>(); }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top