(This is probably a duplicate, but I could not find it), feel free to specify it)
Consider the following Java class:
public class A<T0, T1> { public A(T0 t0, T1 t1) { ... } }
Creating this class is easy using something along the lines of new A<Integer, String>(1, "X")
.
Suppose now that most instances of this class have String
as the second parameter of type T1
and that the object of this type used in the constructor call is also pretty standard.
If A
did not use generics, the general extension would be an additional constructor without a second argument:
public class A { public A(int t0, String t1) { ... } public A(int t0) { this(t0, new String("X")); } }
Unfortunately, this does not seem possible for a class that uses generics - at least without coercion:
public A(T0 t0) { this(t0, (T1)(...)); }
Cause? Although this constructor accepts only one argument, it still uses two type parameters, and there is no way to know a priori that any type of T1
class resource user will be compatible with the default value used in the constructor.
A slightly more elegant solution involves using a subclass:
public class B<T0> extends A<T0, String> { ... }
But this approach forces another branch in the class hierarchy and another class file with what is mainly a code template .
Is there a way to declare a constructor that forces one or more type parameters for a particular type? Something with the same effect as using a subclass, but without the hassle?
Is there anything fundamentally wrong with my understanding of generics and / or my design? Or is this a real problem?