4

I have several interfaces like

interface CanFly{ .. }
interface CanRun{ .. }

and a lot of implementations (done by others)

class Dog implements CanFly{ .. }
class Duck implements CanFly, CanRun{ .. }

Now at some point I need to use a generic which requires types that implement two interfaces.

 class FlyAndRunHandler <ANIMAL extends CanFly AND CanRun>{
    void performAction(ANIMAL animal){
       animal.fly();
       animal.run();
    }
 }

In Scala it would look like ANIMAL extends CanFly with CanRun. Is there a way to archive this in Java. If required I could write additional interfaces but there is no way to add them to the animal classes.

Marcel
  • 4,054
  • 5
  • 36
  • 50
  • 2
    could be this is what you are looking for http://stackoverflow.com/questions/745756/java-generics-wildcarding-with-multiple-classes – Ash Oct 11 '16 at 12:22

1 Answers1

3

you can use Multiple Bounds like <T extends CanFly & CanRun>

Note: in future if you want to add a class along with CanFly & CanRun then make sure to put the class at the beginning like <T extends className & CanFly & CanRun> otherwise it will raise an exception

Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68