I can’t understand why I’m getting this compilation error
Bound mismatch: The generic method
element(T)of typeResourceis not
applicable for the arguments (Class<Chassis>). The inferred
typeClass<Chassis>is not a valid substitute for the
bounded parameter<T extends Resource>.
with the following code:
public class Resource {
protected abstract class has<T extends Resource> {
public has(T v) {}
}
protected <T extends Resource> has element(T v) {
return new has<T>(v) {};
}
}
class Car extends Resource {
has chassis = element(Chassis.class);
}
class Chassis extends Resource {
}
Why is this invalid? Chassis extends Resource, so why doesn’t match to <T extends Resource>?
And how could I constraint element() method to accept as an argument a Resource class object or any Resource subclass object?
Chassis.classis an instance ofjava.lang.Class, which only extendsjava.lang.Object.The
<T extends Resource>expects an actual instance ofResource(or one of its subclasses).To solve this, you can change your method declaration to the following: