1

Why is this causing compilation error:

public <S super T> void addImplements(Class<S> cl)

whereas this is OK:

public <S extends T> void addImplementedBy(Class<S> cl)

T is a type parameter specified on the class. Error message on the first is Syntax error on token "super", , expected

update

This is apparently OK:

public void addImplements(Class<? super T> cl)

Which is essentially the same but without the named type S.

Why is the first variant not allowed or supported? It would appear that technically it is perfectly possible to support it. So is it invalid by design or just not supported (yet)?

I'm not getting the "doesn't buy you anything" from the linked duplicate answer. For one it buys me a named type S that I can use. The second variant (? super T) doesn't offer that.

Note same in Java7 and Java8

3
  • 2
    Possible duplicate of Java generic methods: super can't be used? Commented Oct 11, 2015 at 17:42
  • What would be your use case for doing this ? Commented Oct 11, 2015 at 17:42
  • updated the question to show alternative way that does compile, although without named type S Commented Oct 11, 2015 at 17:51

1 Answer 1

2

The Java Language Specification for Java SE 8 defines a Type parameter with:

TypeParameter:
{TypeParameterModifier} Identifier [TypeBound]

and a Type Bound with:

TypeBound:
extends TypeVariable
extends ClassOrInterfaceType {AdditionalBound}

So the keyword super is explicitly not allowed. The reason is given by the Angelika Langer FAQ on Java Generics:

Type parameters can have several upper bounds, but no lower bound. This is mainly because lower bound type parameters of classes would be confusing and not particularly helpful.

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

1 Comment

+1 for syntax reference. Not sure though I like "confusing" as a valid argument here (unless they mean it would confuse the parser but I don't believe that). Confusing the programmer is not a valid argument IMHO. public <S extends List<Map<T, ArrayList<T>>>> getStuff() can be pretty confusing as well. I simply need to pass an implemented interface of my T class and label it S.

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.