Tuesday 18 March 2014

Type Erasure

Type Erasure is a process, where Java Compiler replaces each with its first bound if the type parameter is bounded, or Object if the type parameter is unbounded.

Box.java

public class Box<T> {

    private T data;

    public Box(T data) {
        this.data = data;
    }

    public T getData() { return data; }

}

In the Class Box.java, “T” is unbounded type. So Java Compiler replaces Every Occurrence of T with Object.


public class Box {

    private Object data;

    public Box(Object data) {
        this.data = data;
    }

    public Object getData() { return data; }

}

Consider one more Example

public class Box<T extends Integer> {

    private T data;

    public Box(T data) {
        this.data = data;
    }

    public T getData() { return data; }

}
 
After type Erasure,Type Parameter “T” change like below.
 
BoxInteger1.java

public class Box{

    private Integer data;

    public Box(Integer data) {
        this.data = data;
    }

    public Integer getData() { return data; }

}

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment