Reputation: 103
I am trying to understand the concept of Bridge Method creation, and was stuck on the example given on the Oracle Java Docs.
Below are the example for reference
Given are the following two classes:
public class Node<T> {
private 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);
}
}
Then it's written that due Type erasure the classes after complilation should become as below:
After type erasure, the Node and MyNode classes become:
public class Node {
private 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(Integer data);
super.setData(data);
}
}
So to preserve the polymorphism, a bridge method is entered in Class MyNode
class MyNode extends Node {
// Bridge method generated by the compiler
//
public void setData(Object data) {
setData((Integer) data);
}
public void setData(Integer data) {
System.out.println("MyNode.setData");
super.setData(data);
}
// ...
}
Below are my questions, on how is it solving the polymorphism? Suppose I call setData using the below code
MyNode mn = new MyNode(5);
mn.setData(new Integer(6));
which method will be called from MyNode, setData(Integer data) or setData(Object data)?
When super.setData(data) is called from setData(Integer data) in Class MyNode, how that is getting resolved, because due to Type Erasure there is no setData(Integer int) in the super Class Node? It seems that the polymorphism problem which was explained will still remain after insertion of the Bridge Method by the compiler. Any help/explaination is really appreciated. Thanks!!
Upvotes: 4
Views: 373
Reputation: 298539
If you have code like
MyNode mn = new MyNode(5);
mn.setData(new Integer(6));
It will call the method setData(Integer)
you have explicitly declared. Things get more interesting for code like:
Node<Integer> mn = new MyNode(5);
mn.setData(new Integer(6));
Since, after type erasure, the class Node
has no method setData(Integer)
, the method setData(Object)
will be invoked. This is where the bridge method comes into play:
In order to invoke the desired method MyNode.setData(Integer)
instead of Node.setData(Object)
(this is the intended polymorphism), the class MyNode
has a synthetic bridge method which overrides setData(Object)
and invokes setData(Integer)
.
Upvotes: 7