Reputation: 7630
Why compiler not stopped to write such code and throw runtime error.
public class GenericTest<T,S> {
T x;
S y;
public GenericTest(T x,S y) {
this.x=x;
this.y=y;
}
void display(){
System.out.println("Display->"+((int)x)+y); //why does it throw error runtime instead of compile time?
}
}
When calling this will obviously failed.
public class Test {
public static void main(String[] args) {
GenericTest<String, String> s=new GenericTest<String, String>("Hello","World");
s.display();
}
}
why does it allowed to type cast for generic type:
System.out.println("Display->"+((int)x)+y);
Upvotes: 0
Views: 77
Reputation: 17622
Because
GenericTest<Integer, Integer> s = new GenericTest<Integer, Integer>(new Integer(1), new Integer(2));
s.display();
is a valid code and it will produce an output.
Also T
and S
are unbouded generics and they are equivalent to Object
.
Object
can be cast to Integer
.
Object o = ...;
Integer i = (Integer) o;
Further more, since Java 7, object can be cast to int
. Hence there was no compilation error.
Your code is equivalent to
class GenericTest {
Object x;
Object y;
public GenericTest(Object x,Object y) {
this.x=x;
this.y=y;
}
void display(){
System.out.println("Display->"+((int)x)+y);
}
}
Upvotes: 3