Rishab Shinghal
Rishab Shinghal

Reputation: 591

Using interface as Bounding Type in a Generic class

public class CollectionsOutput {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here



        //A.display(2,3);



    }

}
interface B
{

}
class A implements B
{

}
class C <T & B>
{

}

In above Java program I am getting compile error in class C declaration. ( as '>' expected) . But I think we can also specify interfaces also as bounding types in Generics, but it's not working. Please help me in this.

Upvotes: 1

Views: 255

Answers (3)

rgettman
rgettman

Reputation: 178303

With generics and bounds, & is only used in between multiple bounds for a generic type parameter declaration.

If you meant that T has to be a subtype of B, then use extends:

class C<T extends B> {}

You might expect it to be something like this:

class C<T implements B> {}  // INCORRECT

because that's how you normally have a class implement an interface.

class Concrete implements AnInterface {}

But when specifying bounds for a generic type parameter, you must use extends, not implements.

Using & would be appropriate with multiple bounds, e.g.:

interface D {}
class C<T extends B & D> {}

Note that when using multiple bounds, any extra bounds beyond the first must be an interface type, not a class or another type variable.

Upvotes: 4

Roman Puchkovskiy
Roman Puchkovskiy

Reputation: 11865

Intersection types A & I & ... are only allowed in constructs like C extends A & I & ... to specify more than one bound.

For example:

public class C<T extends Number & Serializable> {

}

This means that C is parameterized by some type that extends Number and implements Cloneable at the same time.

Another example:

public <T extends Number & Cloneable> void doSomething(T cloneableNumber) {

}

Here double restriction is applied to parameter type.

Your case does not use a type bound, so intersection type cannot be used.

Upvotes: 0

Makoto
Makoto

Reputation: 106470

You likely meant <T extends B> as a way to ensure that whatever type you passed as a generic was still attached to your marker interface.

Upvotes: 1

Related Questions