0
class Gen<T>
{
   T val;
    Gen(T ob)
    {
       val=ob;
    }
    T getOb()
    {
        System.out.println(val.getClass().getName());
        return val;
    }

}

Now suppose in the main method if we do following:

Gen<Float> a=new Gen(2.5);
a.getOb()

I get output as

java.lang.Double

Exception in thread "main" java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Float

If "java.lang.Double" is printed it means T was replaced with Double, but we say it should have been replaced with raw type i.e. Object?

What is the reason of this runtime exception?

Please help me in digesting this.

Rishab Shinghal
  • 591
  • 3
  • 16
  • Don't use `new Gen(...)`: always use `new Gen<>(...)` or `new Gen(...)` when the class is generic. – Andy Turner Feb 17 '18 at 08:36
  • Hey Andy, Can you explain the reason that if T is getting replaced as Double, then why it is returning Float, even though return type is also T-> Double. – Rishab Shinghal Feb 17 '18 at 08:58
  • The line`System.out.println(val.getClass().getName());` never outputs the type of T, it always outputs the class of `val`. Consider `Gen a = new Gen<>("Test"); a.getOb();`: this compiles and runs without a problem, and even though T is clearly `Object` it will print out `java.lang.String` – Thomas Kläger Feb 17 '18 at 13:12

0 Answers0