P
P
pqgg7nwkd42016-08-18 18:33:09
Java
pqgg7nwkd4, 2016-08-18 18:33:09

Why does a class generic affect a method's own generic?

Question by example:

static class Foo<T> {
        <R> R get(R value) {
            return value;
        }
    }

    static {
        {
            // Так работает:
            Foo<?> foo = new Foo<>();
            Long a = foo.get(123L);
        }
        {
            // Так работает:
            Foo<String/*любой тип*/> foo = new Foo<>();
            Long a = foo.get(123L);
        }
        {
            // А почему так не работает?
            Foo foo = new Foo();
            Long a = foo.get(123L); // -- incompatible types Long и Object
        }
    }

Why does the absence of a class generic when defining a variable prevent the use of a method that this generic does not affect?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly Vitrenko, 2016-08-19
@Vestail

If you use a raw reference, you lose the ability to use generics for any non-static class members through that reference. JLS(4.8)
Combining Raw Types and Generic Methods

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question