Reputation: 998
Suppose I have the following classes:
public abstract class AbstractClass {
...
}
public class ConcreteClass extends AbstractClass {
...
}
a builder:
public class Builder{
static public ConcreteClass build(){
...
}
}
and a generic function in some other class:
public <T extends AbstractClass> T myFunction(){
T a = Builder.build();
return a;
}
It was my understanding that the compiler should have enough information to allow such assignment, however, it throws an error:
Type mismatch: cannot convert from ConcreteClass to T
Why is that and what are the potential dangers of such assignment?
Upvotes: 0
Views: 68
Reputation: 58858
Someone could write this:
public class OtherConcreteClass extends AbstractClass {
...
}
...
SomeOtherClass soc = SomeOtherClass.<OtherConcreteClass>myFunction();
In that call to myFunction, T is OtherConcreteClass, and you can't cast ConcreteClass to OtherConcreteClass.
Upvotes: 2
Reputation: 11454
In short: T doesn't have to be ConcreteClass, it could also any sibling of ConcreteClass (e.g. if you declared ConcreteClass2 that also extended ConcreteClass).
Upvotes: 0