0
votes

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?

1
Why should it raise an error?Louis Wasserman

1 Answers

2
votes

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.