Dimitri
Dimitri

Reputation: 1966

Generic static methods within a generic class

Suppose I have:

public class Parent<T extends Child1>  {
    public Parent() {       
    }

    public static <T extends Number> void test(T t) {
    }
}

And Child1 is a child class of Parent.

What I'm trying to understand here is the connection between the parameter type T in both class scope and method scope. How can both parameters (class' and method's) be allowed to be named T if their bounds are completely different from one another?

Upvotes: 4

Views: 70

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213233

The type parameter defined in the method is completely independent of the one defined in the class. In fact, you've to define type parameter for static methods, as class-level type parameters can't be used there. You can't use class-level type parameter in static context. That's outside their scope. So, if you remove that method level type parameter declaration, you'll get a compilation error.

Upvotes: 6

Related Questions