Difference between void foo(T y) and <T> void foo(T y) in Java generic class

generics, java, object-oriented-analysis

Solution

class C<T>{
    T x;
    <T> void foo(T y)  { … }
}

is a confusing way to write

class C<T>{
    T x;
    <S> void foo(S y)  { … }
}

as for what would reject the second version, for example this:

class C<T>{
    T x;
    <T> void foo(T y)  { x = y; }
}

will fail, because if you rewrite it as

class C<T>{
    T x;
    <S> void foo(S y)  { x = y; }
}

you can immediately see that you're missing a cast (the exact compiler error is "incompatible types").

Problem

Explain in detail the difference, if any, between the following two versions of a Java generic class? ``` class C<T>{ T x; void foo(T y) { … } } ``` and ``` class C<T>{ T x; <T> void foo(T y) { … } } ``` and another question: What could be written in the body of foo(), replacing the “…” that would cause the Java compiler to accept the first version of C but reject the second version of C. I'm very puzzled.

Original source