Binding generic parameter to more than 1 type

suggest change

Generic parameters can also be bound to more than one type using the T extends Type1 & Type2 & ... syntax.

Let’s say you want to create a class whose Generic type should implement both Flushable and Closeable, you can write

class ExampleClass<T extends Flushable & Closeable> {
}

Now, the ExampleClass only accepts as generic parameters, types which implement both Flushable and Closeable.

ExampleClass<BufferedWriter> arg1; // Works because BufferedWriter implements both Flushable and Closeable

ExampleClass<Console> arg4; // Does NOT work because Console only implements Flushable
ExampleClass<ZipFile> arg5; // Does NOT work because ZipFile only implements Closeable

ExampleClass<Flushable> arg2; // Does NOT work because Closeable bound is not satisfied.
ExampleClass<Closeable> arg3; // Does NOT work because Flushable bound is not satisfied.

The class methods can choose to infer generic type arguments as either Closeable or Flushable.

class ExampleClass<T extends Flushable & Closeable> {
    /* Assign it to a valid type as you want. */
    public void test (T param) {
        Flushable arg1 = param; // Works
        Closeable arg2 = param; // Works too.
    }

    /* You can even invoke the methods of any valid type directly. */
    public void test2 (T param) {
        param.flush(); // Method of Flushable called on T and works fine.
        param.close(); // Method of Closeable called on T and works fine too.
    }
}

Note:

You cannot bind the generic parameter to either of the type using OR (|) clause. Only the AND (&) clause is supported. Generic type can extends only one class and many interfaces. Class must be placed at the beginning of the list.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents