5

The following Java code compiles:

interface Interface1{}
interface Interface2{}
class MyClass1<T extends Interface1 & Interface2>{}

Also, the following code compiles:

class AClass{}
interface Interface3{}
class MyClass2<T extends AClass & Interface3>{}

The following code will give me a compile error:

interface Interface4 {}
class MyClass3<T, S extends T & Interface4> {}

So, as it seems, it is not possible to have multiple bounds if one of the bounding types is itself a type parameter. But why is that?

As I understand, if multiple bounds are declared, at most one of them may be a class (with all others being interfaces), and it must be the first one.

But, since in my example Interface is an interface, why does the compiler complain? After all, it shouldn't make any difference whether T is an interface or a class.

I've tried to find an answer online, but apparently my googling skills are not sufficient. I'd love to understand what's going on here.

Michael
  • 41,989
  • 11
  • 82
  • 128
fritteli
  • 113
  • 7

1 Answers1

5

Section 4.4 of the Java language spec seems to explicitly disallow this. A Type Bound is specified as:

TypeBound:
   extends TypeVariable
   extends ClassOrInterfaceType {AdditionalBound}

AdditionalBound:
   & InterfaceType

So it looks like you can specify a Type Variable ("T"), or you can have a list of classes and interfaces, but you can't mix them.

https://docs.oracle.com/javase/specs/jls/se18/html/jls-4.html#jls-4.4

markspace
  • 10,621
  • 3
  • 25
  • 39
  • I understand why they have done this, but having this feature would be really powerful. How would one go about making/requesting this change? – davidalayachew May 05 '22 at 22:02