As everyone knows you can have a generic class in Java by using type arguments:
class Foo {
T tee;
Foo(T tee) {
this.tee = tee;
}
}
But you can also have generic constructors, meaning constructors that explicitly receive their own generic type arguments, for example:
class Bar {
Bar(U you) {
// Why!?
}
}
I'm struggling to understand the use case. What does this feature let me do?
解决方案
What does this feature let me do?
There are at least three two things it lets you do that you could not otherwise do:
express relationships between the types of the arguments, for example:
class Bar {
Bar(T object, Class type) {
// 'type' must represent a class to which 'object' is assignable,
// albeit not necessarily 'object''s exact class.
// ...
}
}
As @Lino observed first, it lets you express that arguments must be compatible with a combination of two or more unrelated types (which can make sense when all but at most one are interface types). See Lino's answer for an example.