Gmacar
Gmacar

Reputation: 223

Type parameter with multiple bounds

This code compiles:

import java.io.Serializable;
import java.util.Arrays;
class Test<T extends Arrays & Serializable> { }

but if I replace the last line with

class Test<T extends Serializable & Arrays> { }

I get "interface expected here". Why?

Upvotes: 8

Views: 1585

Answers (2)

Andrew
Andrew

Reputation: 38029

If one of the bounds is a class, it must be specified first.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503419

From section 4.4 of the JLS:

Every type variable declared as a type parameter has a bound. If no bound is declared for a type variable, Object is assumed. If a bound is declared, it consists of either:

  • a single type variable T, or

  • a class or interface type T possibly followed by interface types I1 & ... & In.

It is a compile-time error if any of the types I1 ... In is a class type or type variable.

So basically, if your bounds include a class, it has to be the first bound.

(Given that Arrays can't be instantiated, it's unclear why you would want a bound including it, mind you... was this just an example?)

Upvotes: 13

Related Questions