Search code examples
javajlsstatic-initializer

Type variable declared outside the static initialiser within the static initialiser


Could anyone give an concrete example as to what the following text in the JLS (§8.7) means?

It is a compile-time error if [...] any type variable declared outside the static initializer, appears anywhere within a static initialiser.

And what would be the the reason for making it an error?


Solution

  • A type variable is unqualified identifier used by the class. Instances of the class may have different actual types substitute the type variable. Type variables only apply to instances of the class. So, they can not be referenced in the static context of the same class. This would be an example of this error:

    import java.util.*;
    public class Test<N> {
      static { List<N> p = new ArrayList<>(); }
    }