0

Here is a code sample:

public class TypeErasure<X extends String>{
    private X data;

    public TypeErasure(String s){
        this.data = s;
    }

According to me, after type erasure the code should look like this:

public class TypeErasure{
    private String data;

    public TypeErasure(String s){
        this.data = s;
    }

But I get a compile time error saying

Error:(139, 25) java: incompatible types: java.lang.String cannot be converted to X

Once type erasure is done, information about X is lost, so why does the compiler complain?

Amit
  • 469
  • 1
  • 5
  • 19
  • 2
    You're declaring `X` to be subtype of `String`, and then assign a `String` to a field of that subtype. It's not a question of type erasure... – jp-jee Nov 27 '16 at 16:28
  • 1
    String is a final class. How "X extends String" could be valid? – selimssevgi Nov 27 '16 at 16:31
  • I don't follow why it is not type erasure. Isn't it true that X will be replaced by String by the compiler? – Amit Nov 27 '16 at 16:34
  • 1
    @Amit No. Type erasure means after compilations, `X` is replaced by `Object`. – Elliott Frisch Nov 27 '16 at 16:35
  • 1
    @ElliottFrisch That answers my question. Thanks. – Amit Nov 27 '16 at 16:36
  • Think about it. The entire Generics exist to allow the compiler to do type checking. Doing the check after erasure would imply the same state as before Generics were introduced. Do you think this would make any sense? – Holger Jan 30 '17 at 17:16

1 Answers1

2

Once type erasure is done, information about X is lost, so why does the compiler complain?

Your observation answers your main question:

Is type erasure done before the Java compiler does type checking?

Evidently, the type checking happens before the type is erased, that why you get an error.

You can read more about this in the sub-section of the relevant documentation.

See also this other answer on the topic.

Community
  • 1
  • 1
janos
  • 109,862
  • 22
  • 193
  • 214