Blizzer
Blizzer

Reputation: 260

Assignment isn't working using generics in a simple way

I would very apprciate if someone could explain to me why u = bar(u,r) in following code isn't working. I just can't find the right explanation.

class R {
}

class U {
}

public class Foo {

    public static <T> T bar(T x, T y) {
        return x;
    }

    public static void main(String[] args) {

        R r = new R();
        U u = new U();

        u = bar(u,r); // why is this not working?
    }
}

UPDATE:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Type mismatch: cannot convert from Object to U

Upvotes: 2

Views: 91

Answers (1)

Keppil
Keppil

Reputation: 46219

When figuring out which type to use for the generic type T, Java looks at the types of the arguments.

In this case, the arguments u and r are of different, unrelated types (U and R).

Their closest common ancestor is therefore Object, so the return type will be Object, which needs a cast to be able to be assigned to u.

Upvotes: 7

Related Questions