Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma or ampersand with multiple bounded types?

Tags:

java

types

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>
like image 863
terminex9 Avatar asked Mar 05 '15 05:03

terminex9


People also ask

Is it possible to declared a multiple bounded type parameter?

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.

Which of these is the correct way to declare a bounded type?

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 .

When it is required to restrict the kinds of types that are allowed to be passed to a type parameter are used?

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.

What are bounded types?

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.


2 Answers

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

like image 195
ajb Avatar answered Oct 23 '22 17:10

ajb


Multiple Bounds are possible with <T extends B1 & B2 & B3> where B2 and B3 should be interface. B1 can be simple class or interface

like image 6
M Sach Avatar answered Oct 23 '22 17:10

M Sach