Brooklyn Wang Brooklyn Wang - 3 months ago 15
Java Question

Confused about Type Erase and Bridge Methods

The Java™ Tutorials
https://docs.oracle.com/javase/tutorial/java/generics/bridgeMethods.html
shows an example:

public class Node<T> {

public T data;

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

public void setData(T data) {
System.out.println("Node.setData");
this.data = data;
}
}

public class MyNode extends Node<Integer> {
public MyNode(Integer data) { super(data); }

public void setData(Integer data) {
System.out.println("MyNode.setData");
super.setData(data);
}
}


After type erasure, the Node and MyNode classes become:

public class Node {

public Object data;

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

public void setData(Object data) {
System.out.println("Node.setData");
this.data = data;
}
}

public class MyNode extends Node {

public MyNode(Integer data) { super(data); }

public void setData(Integer data) {
System.out.println("MyNode.setData");
super.setData(data);
}
}


After type erasure, the Node method becomes setData(Object) and the MyNode method becomes setData(Integer).

Why does the MyNode method not become setData(Object)? Why does "Integer" not be erased?

Thanks a lot.

Answer

Why does the MyNode method not become setData(Object)? Why does "Integer" not be erased?

MyNode's setData is defined as :

public void setData(Integer data)

i.e. it has no generic type parameters. Therefore there is nothing to be erased. The data argument remains Integer.