Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type parameter with multiple bounds

Tags:

java

generics

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?

like image 973
Gmacar Avatar asked Apr 02 '12 11:04

Gmacar


People also ask

Can a parameterized type have several bounds?

A type parameter can have multiple bounds.

What is a bounded type parameter?

There may be times when you want to restrict the types that can be used as type arguments in a parameterized type. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for.

What are bounded type parameters in generic?

Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class. These are known as bounded-types in generics in Java.

What is the difference between a wildcard bound and a type parameter bound?

What is the difference between a wildcard bound and a type parameter bound? A wildcard can have only one bound, while a type parameter can have several bounds. A wildcard can have a lower or an upper bound, while there is no such thing as a lower bound for a type parameter.


1 Answers

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?)

like image 50
Jon Skeet Avatar answered Oct 13 '22 00:10

Jon Skeet