11
package org.my.java;

public class TestTypeVariable {

    static <T,A extends T> void typeVarType(T t, A a){
        System.out.println(a.getClass());
        System.out.println(t.getClass());
    }

    public static void main(String[] s){
        int i= 1;
        typeVarType("string", i);
    }
}

when run, following is the output :

class java.lang.Integer
class java.lang.String

How can A be of type Integer when it has been already upper-bounded to String?

Please explain me on it.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
Atul
  • 521
  • 1
  • 7
  • 20

1 Answers1

15

Two things here:

  • there is a simple solution to the "bad" typing: T isn't String but Object. And Integer extends Object. But please note: this only works with the "enhanced" type inference capabilities of Java8. With Java7, your input will not compile!
  • misconception on your end: getClass() happens at runtime, and therefore returns the specific class of the objects passed - independent on what the compiler thinks about generics at compile time.
GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • It compiles fine. `typeVarType("string", i);` has `T=Object, A=Integer` . – khelwood Sep 25 '17 at 08:20
  • it is compilable and runable. getClass() i just used to print run-time type of an object.but thats not an issue. main point is how java allowing integer type for an string upper bounded type – Atul Sep 25 '17 at 08:22
  • @khelwood That happens when one believes in other comments without further checking. I thought "T should be Object" myself ... thanks, and updated. – GhostCat Sep 25 '17 at 08:22
  • 2
    It compiles fine in Java 8, but doesn't pass compilation in Java 7. In this case I think it makes more sense for it not to pass compilation, since `` makes no sense (due to type erasure). – Eran Sep 25 '17 at 08:26
  • Of course, the inferred type for `T` could also be `Object & Serializable & Comparable>`… – Holger Sep 25 '17 at 13:46
  • I wish you could quote the JLS here, i swear given this on an interview I would say it fails – Eugene Sep 25 '17 at 19:58