Generics and ClassCastException

Viewed 428

Given the following piece of code:

public class ClassCastTest {

    private static class GenericHolder<T> {
        private T object;

        public GenericHolder(Object object) {
            this.object = (T) object;
            System.out.println(getObject());
        }

        public T getObject() {
            return object;
        }
    }

    public static void main(String[] args) {
        GenericHolder<String> foo = new GenericHolder<>(3l);
        System.out.println(foo.getObject());
    }

}

Why does Java throw a ClassCastException in the second line of the main-method instead of the second line of the GenericHolder?

2 Answers
Related