Kundan Singh
Kundan Singh

Reputation: 21

Generics Classes in Java

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

Upvotes: 2

Views: 49

Answers (1)

Eran
Eran

Reputation: 393781

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.

Upvotes: 3

Related Questions