Bounded type parameters allow you to set restrictions on generic type arguments:
class SomeClass {
}
class Demo<T extends SomeClass> {
}
But a type parameter can only bind to a single class type.
An interface type can be bound to a type that already had a binding. This is achieved using the &
symbol:
interface SomeInterface {
}
class GenericClass<T extends SomeClass & SomeInterface> {
}
This strengthens the bind, potentially requiring type arguments to derive from multiple types.
Multiple interface types can be bound to a type parameter:
class Demo<T extends SomeClass & FirstInterface & SecondInterface> {
}
But should be used with caution. Multiple interface bindings is usually a sign of a code smell, suggesting that a new type should be created which acts as an adapter for the other types:
interface NewInterface extends FirstInterface, SecondInterface {
}
class Demo<T extends SomeClass & NewInterface> {
}