A list with a parameter that extends several types

Using common methods, you can extend several types, for example:

<T extends MyClass & MyInterface> void foo(T bar)

Is it possible to specify a list with a parameter that extends several types?

List<MyClass & MyInterface> myList;

does not work...

This will do the following:

class A extends MyClass implements MyInterface{}

class B extends MyClass implements MyInterface{}

myList.add(new A());
myList.add(new B());

MyClass c = myList.get(index);
MyInterface i = myList.get(index);

foo(myList.get(index));
+3
source share
2 answers

The answer is NO.

Depending on your semantic expectation, you will find a workaround

One possible workaround for foo

   <T extends MyClass> void foo(T bar) {
     if (bar instanceof MyInterface) return;
   }

Probably the best approach is to create a type that exposes both types. The disadvantage is that all interesting classes must be derived from this class

abstract class MyClassInterface extends MyClass implements MyInterface {}

List<MyClassInterface> myList;


<T extends MyClassInterface> void foo(T bar)

The naive approach only to provide both methods will cause ambiguity, so it is not possible (for "And", for "XOR" this would be true)

<T extends MyClass> void foo(T bar)

<T extends MyInterface> void foo(T bar)
+3
source

, ( T extends TopMostBase).

, ( List<?> myList , , ).

+3