0

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);
bNd
  • 7,512
  • 7
  • 39
  • 72
  • When `GenericTest` is compiled, how would the compiler know you will be using a class which can't be cast? – Peter Lawrey Jan 08 '16 at 13:05
  • 1
    This program will work if you pass Integer... that will be due to autoboxing. So compiler has a valid usecase to not throw a compile time error – awsome Jan 08 '16 at 13:07
  • I know it's work with integer. But why does Java allow cast to generic of class definition in class itself as its definition says this will be allowed to construct with any type? – bNd Jan 09 '16 at 01:50

1 Answers1

3

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); 
        }
}
Community
  • 1
  • 1
sanbhat
  • 17,522
  • 6
  • 48
  • 64