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?
A type parameter can have multiple bounds.
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.
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? 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.
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?)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With