2

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.

3
  • 1
    Add the link of JLS here. Otherwise, it's hard to know the context Commented Apr 12, 2014 at 15:31
  • I have a copy available at the office which I cannot share. This sentence appears in the section where static modifier for a method is explained. Commented Apr 12, 2014 at 15:36
  • docs.oracle.com/javase/specs/jls/se7/html/jls-8.html point 8.4.3.2 Commented Apr 12, 2014 at 15:39

1 Answer 1

5

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) {
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Paul, Thanks for the clarification. Does this mean I can use any other generic type in a static method than the one used by the class?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.