0

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?

Joel
  • 4,732
  • 9
  • 39
  • 54
M T
  • 968
  • 1
  • 8
  • 24
  • Why are you trying to make it generic on T, when you just want to return `AbstractClass`? – Elliott Frisch Jan 27 '14 at 22:12
  • 1
    As you are trying to use a builder pattern with inheritance maybe [this post here](http://stackoverflow.com/questions/21210870/in-java-can-you-use-the-builder-pattern-with-required-and-reassignable-fields/21211472#21211472) might help, although it was a bit misplaced in that post as I understood the question fully after having posted this. – Roman Vottner Jan 27 '14 at 22:18
  • Maybe example is a little bit too simplified, I just wanted to show example of assignment part, everything else is irrelevant. – M T Jan 27 '14 at 22:35

2 Answers2

2

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.

user253751
  • 57,427
  • 7
  • 48
  • 90
0

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).

Sbodd
  • 11,279
  • 6
  • 41
  • 42