Any ideas why the code below doesn’t compile?
public class A<TT extends B<?>> extends C<TT> implements D<TT> {
protected A(Class<TT> c) {
super(c);
}
}
interface B<MM> {
}
interface D<MM extends B<?>> {
}
abstract class C<TT> {
protected C(Class<TT> c) {
}
}
class F implements B<String> {
}
class G extends F {
}
class E<TT extends B<String>> {
public E() {
// why does this not work?
// Error: The constructor A<TT>(Class<G>) is undefined
D<TT> d = new A<TT>(G.class);
}
}
Simple:
G.classis aClass<G>– not aClass<TT>.This works:
… but you don’t know the type of
TT(in E) so you can’t provide the relevantClass<TT>instance to theA<TT>constructor. This would compile too, but probably isn’t what you want:Imagine we tried to use your current code, and had:
Then it would be entirely reasonable to construct an
E<H>, but you’d be trying to passG.classto the constructor ofA<H>– it’s clearly not the same type.(As a side-note, it’s really helpful to make these examples as simple as possible. That means getting rid of all the classes which aren’t relevant, and avoiding reusing type parameter names for the sake of clarity.)