3

Suppose I have the following code snippet

Number n=new Integer(2);

then when I use the code ,its shows an error

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

but if below code works fine

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

Why is it so ? Please explain in some simple & precise words.

1 Answers1

2

Well, the class of an Integer is Class<Integer> which is different from Class<Number>. Because n can contain any kind of Number, its class can be any class that extends Number.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
  • If you are like me and not able to understand what difference it makes, take a look at [this answer](http://stackoverflow.com/a/21351277/2775450) which explains why `? extends Something` matters. – Codebender Jul 10 '15 at 15:21