pvgoddijn
pvgoddijn

Reputation: 12898

How can I accept a supertype of generic parameter on a single object?

Is it possible to accept only supertypes of the generic Type of a class?

What I'm looking for is something like:

class <T extends Object> MyClass {

    public <TS super T> void myMethod(TS someObjectSuperToTheClass) {
         //do stuff
    }

}

I don't really need it anymore (and it's probably not all that useful to begin with) but I'm curious if this is at all possible and if not, why.

Upvotes: 0

Views: 227

Answers (2)

Andrzej Doyle
Andrzej Doyle

Reputation: 103777

Think about what it would mean in this case.

You want to assert that TS is either T, or any of its superclasses. But since TS is merely a reference, the actual someObjectSuperToTheClass parameter can be TS or a subclass.

Putting both halves together, in comes out that your code is entirely equivalent to

public void myMethod(Object someObjectSuperToTheClass) { //do stuff }

since together, you've got that TS can walk as high as it wants up the class hierarchy, and the parameter can walk down as far as it wants.

What was it you were trying to constrain the parameter to, with this syntax?

Upvotes: 6

notnoop
notnoop

Reputation: 59299

No you cannot! Only wildcards can have a super bound.

Upvotes: 3

Related Questions