Question

I read in the JLS 7 the following sentence.

It is a compile-time error to use the name of a type parameter of any surrounding declaration in the header or body of a class method.

Please explain its meaning.

Was it helpful?

Solution

It means you can't do

class Test<T> {
    static void f(T a) {
    }
}

You have to do

class Test<T> {
    static <T> void f(T a) {
    }
}

The generic types of a static method are independent of generic types of the class or other methods.

So you can even do something like

class Test {
    static <A, B, C> void f(A a, B b, C c) {
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top