I am new to java.I still feel I have to understand a lot so if this question seems stupid forgive me. Now I was going through http://docs.oracle.com/javase/tutorial/java/generics/bridgeMethods.html
Here I found a lot of confusion .
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);
}
public static void main(String[] args) {
MyNode mn = new MyNode(5);
Node n = mn; // A raw type - compiler throws an unchecked warning
n.setData("Hello"); // Causes a ClassCastException to be thrown.
Integer x = mn.data;
}
}
When I ran this code I got below error
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at MyNode.setData(MyNode.java:1)
at MyNode.main(MyNode.java:14)
Below are the confusions
1) Why is it showing line number 1
2) If you read through the blog they say that the type erasure will replace type parameter will replace above code as below
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(data);
super.setData(data);
}
public static void main(String[] args) {
MyNode mn = new MyNode(5);
Node n = mn; // A raw type - compiler throws an unchecked warning
n.setData("Hello"); // Causes a ClassCastException to be thrown.
//Integer x = mn.data
}
}
when I run the above code I get no error , code runs fine
from the documentation both r same ? why this different in behavior
now other most important question on oop is when we extend one class and when we call super constructor though super object is not created then what is the use of calling super. Please explain.