Consider the following code
class SomeClass {
}
class GenericsExample<E extends SomeClass> {
public void createError() {
process(new SomeClass()); //Compiler error!
}
public void createWorking() {
E some = new SomeClass(); //Compiler error!
process(some);
}
public void process(E object) {
}
}
public class Sandbox {
public void run() {
new GenericsExample<SomeClass>().process(new SomeClass()); //Not a compiler error?!
new GenericsExample().process(new SomeClass()); //Still not a compiler error?!
}
}
The message for the first error (the second one is essentially the same thing)
required: E
found: SomeClass
reason: actual argument SomeClass cannot be converted to E by method invocation conversion
where E is a type-variable:
E extends SomeClass declared in class GenericsExample
This can be fixed by casting SomeClass to E, but why should I have to? If a method takes E as an argument and E extends SomeClass, shouldn't it accept SomeClass as an argument? Why is this a compiler error instead of a warning?
And why does this not apply to outside classes, even in cases where I don't even declare the generic type? Why are the rules so different in GenericsExample vs Sandbox?