Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generic type and assignment problems

Tags:

java

oop

generics

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 ?

like image 548
Aladdin Avatar asked Dec 26 '22 03:12

Aladdin


2 Answers

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.

like image 165
greedybuddha Avatar answered Jan 08 '23 20:01

greedybuddha


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.

like image 21
andersschuller Avatar answered Jan 08 '23 19:01

andersschuller