Menu
Topics Index
...
`

Type Erasure - Java Example Program


Type Erasure
class GenericsErasureDemo
{
    public static void main(String args[])
    {
    
        GenericsErasure<Integer> integerObject = new GenericsErasure<Integer>(12);
        
        System.out.println("Integer Object : " + integerObject.getClass().getName());
        
        GenericsErasure<Float> floatObject = new GenericsErasure<Float>(23.0F);
        
        System.out.println("Float Object : " + floatObject.getClass().getName());
    
    }
}

class GenericsErasure<T>
{
    T obj;
    GenericsErasure(T obj)
    {
        this.obj =obj;
    }
}
OUTPUT

GenericsErasure
GenericsErasure

DESCRIPTION

Here, the types of integerObject and floatObject are GenericsErasure,not GenericsErasure<Integer> and GenericsErasure<Float>. Remember, all type parameters are erased during compilation. At run time, only raw types actually exist.

THINGS TO TRY
  • Create an instance for Double and try to print the type.

© meritcampus 2019

All Rights Reserved.

Open In App