Generics Classes in Java

Viewed 45

Why isn't the following code throwing an error/exception?

public class UserGenerics <T>
{
    T obj;
    public UserGenerics(T obj) {
        this.obj = obj;
    }
}

class UserGenericsRunner
{
    public static void main(String[] args) {
        UserGenerics<Integer> ug1 = new UserGenerics("StringObject");
        UserGenerics ug2 = new UserGenerics(23);      
    }
}

During the first object creation, a type parameter is passed as an Integer but the object passed to the constructor is a String object

1 Answers

That's because you are creating an instance of a raw type.

You should change

UserGenerics<Integer> ug1 = new UserGenerics("StringObject");

to

UserGenerics<Integer> ug1 = new UserGenerics<>("StringObject");

or

UserGenerics<Integer> ug1 = new UserGenerics<String>("StringObject");

and the compiler will give a compilation error.

Related