Unable to understand the use of Java templates?

Suppose I have the following piece of code

Number n=new Integer(2);

      

then when i use the code it shows an error

Class<Number> hi=n.getClass(); //type mismatch error

      

but if the code below works fine

Class<? extends Number> hi=n.getClass();

      

Why is that? Please explain in a few simple and precise words.

+3


source to share


1 answer


Well, the class Integer

is equal Class<Integer>

, which is different from Class<Number>

. Since it n

can contain any type Number

, its class can be any class that extends Number

.



+2


source







All Articles