Menu
Topics Index
...
`


Generics >
Siva Nookala - 15 Apr 2016
Generics was added to provide type-checking at compile time and it has no use at run time, so java compiler uses type erasure feature to remove all the generics type checking code in byte code and insert type-casting if necessary. Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.

The following program shows how the ensure works
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.

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App