I know that , every generic type variable replaced to upper bound that has been determined from the generic definition in the start of method "type-parameter section".
this is from Deitel book
Actually, all type parameters are replaced with the so-called upper bound of the type parameter, which is specified in the type-parameter section.
according to that , this subcode must be true
public static <E extends Number> void A( )
{
E x= new Double(2.2);
}
but the compiler tell me is compilation error in E x= new Double(2.2);, although this must be true because the double is number .
I know how to process and solve the problem in general by casting , but I ask why this occur ?
Just because E
is a number doesn't mean that it is a Double
.
Think of it like this, what if E was an Integer. E is still a Number, but now you are assigning a Double to an Integer. So the casting behavior is consistent, Number can be all sorts of different Types, and so could E.
EDIT for Op: The Deitel statement is still correct, If you were assigning the Double to a Number or to an Object then you wouldn't need casting. In this case though, E is not assigning "upwards" it's assigning "laterally" between two possible different Number types. What if E was a Short, or an Integer, in these cases you wouldnt expect to be able to assign them a Double without casting.
When you specify E extends Number
, this means E
is any subtype of Number
, or Number
itself. For example, E
could be an Integer
, Long
, Double
, etc. This is why your code does not compile - if E
was Integer
, for example, it would be wrong to be able to assign a Double
to the variable of type Integer
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With