Difference between void foo (T y) and <T> void foo (T y) in Java class
Explain in detail the difference, if any, between the following two versions of the Java class:
class C<T>{
T x;
void foo(T y) { … }
}
and
class C<T>{
T x;
<T> void foo(T y) { … }
}
and one more question: what could be written in the body of foo (), replacing "...", which would force the Java compiler to accept the first version of C, but reject the second version of C.
I am very puzzled.
+3
2 answers
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) { … }
}
in order to drop the second version, for example:
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 are missing a role (the exact compiler error is “incompatible types”).
+10