-1

Please look into following code. Why this error is thrown even though Integer is inherited from Number and why the same case of error is not there when '? extends Number' is used.

public class testGeneric
  {
    public static void main(String[] args)
        {
          Class<Integer> classint = int.class;
          Class<Number> classnum1 = int.class;// Error Type mismatch: cannot convert from  
                                              // Class<Integer> to Class<Number>
          Class<? extends Number> classnum2 = int.class;
        }
  }
priyank
  • 11
  • 1
  • 5

2 Answers2

1

You do not have co-variance (if that is the word I am looking for) in generic types.

They need to match exactly.

Class<Number> can only be assigned by Number.class.

If you want to allow subclassed (or superclasses) you have to use extends or super.

Class<? extends Number> can take Integer.class (among others, such as Long.class or Number.class).

Class<? super Number> can take Number.class or Object.class.


This is different from methods of a generic type being able to work on subclass instances.

For example, you can add an Integer into a List<Number>, but that does not make List<Number> assignable to List<Integer> (or vice versa).


An object instance can be used where a superclass is required, but a generic type cannot.

Thilo
  • 257,207
  • 101
  • 511
  • 656
0

According to my understanding

Autoboxing and Unboxing is happening for Integer and int, but it is not possible for Number and int.

For info about autoboxing refer https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

Naman Gala
  • 4,670
  • 1
  • 21
  • 55
  • My question is why there is error even though Integer is sub of Number, and even if the type mismatch is thrown up for some reason than why the code works perfect with extends keyword. – priyank Nov 11 '14 at 05:41
  • 1
    This does not have to do with auto boxing and unboxing. – Radiodef Nov 11 '14 at 06:20