Search code examples
javajavac

Why javac not checks the undeclared TypeParameter in this case?


There is a question related to Java generics. Please see following piece of code.

class Beta{
    
    public void hello(){}
}
class Alpha {
    public <Anything> void greet(Beta beta) {
        beta.hello();
    }

}

In the method greet(), <Anything> is not declared any where. Why does javac not throw any error in this case?


Solution

  • The only occurence of<Anything> is it's declaration. It is declared for the scope of the method but never used.

    Take the following example from the Java Language Specification for a generic method:

    class CollectionConverter {
    <T> List<T> toList(Collection<T> c) {...}
    }
    

    The first <T> declares the type argument. The second and third one use it for the return type and for an argument type.

    Your example is basically just the first <T> without actual usage. A little weird, but not a problem.