4

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?

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This just summed it up for me!
One last thing. Does the same apply for non-static methods, or is defining a generic parameter on a method always exclusive to that method, regardless of their visibility?
@Dimitri Yes, defining a type parameter on any method is independent of the one defined in 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.