In Java, are commas and ampersands both valid when declaring a multiply bounded type?
class MyClass <T extends OtherInterface, SomeInterface>
class MyOtherClass <T extends OtherInterface & SomeInterface>
Multiple BoundsBounded type parameters can be used with methods as well as classes and interfaces. Java Generics supports multiple bounds also, i.e., In this case, A can be an interface or class. If A is class, then B and C should be interfaces. We can't have more than one class in multiple bounds.
To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number .
Bounded Type Parameters There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a type parameter. 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.
As others have pointed out, this:
class MyOtherClass <T extends OtherInterface & SomeInterface>
defines a multiply bounded type parameter. If you use MyOtherClass
, you must give it a type that implements both OtherInterface
and SomeInterface
.
However, this does not define a multiply bounded type parameter:
class MyClass <T extends OtherInterface, SomeInterface>
It defines a generic with two type parameters. The first one must implement OtherInterface
. The second one can be anything. It's just the same as
class MyClass <T extends OtherInterface, U>
except that you named it SomeInterface
instead of U
. (The convention is that type parameters are normally single upper-case letters, or sometimes an upper-case letter and a digit or a short upper-case identifier. But the compiler doesn't care. It won't look at the form of the identifier to figure out that you really meant it as an interface.)
Multiple Bounds are possible with <T extends B1 & B2 & B3>
where B2 and B3 should be interface. B1 can be simple class or interface
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