Question

Is there some "best practice" how to declare a variable implementing two interfaces?

Let's say your method needs an object to implement InterfaceA and InterfaceB at the same time.

void doSomething( BOTH_INTERFACES argument) {
...
}

What do you think is the best way to achieve or simulate this?


I thought of creating a combining interface

interface InterfaceAB extends InterfaceA, InterfaceB {}

But can I then cast the following object to it?

class SomeObject implements InterfaceA, InterfaceB {}

Other ideas:

I could do something like:

void doSomething( Object argument) {
    if(!(argument instanceof InterfaceA) || !(argument instanceof InterfaceB)) {
        throw new IllegalArgumentException();
    }
    InterfaceA faceA = (InterfaceA) argument;
    InterfaceB faceB = (InterfaceB) argument;
    // do some stuff with it
}

Or perhaps this hideousness:

void doSomething( InterfaceA faceA, InterfaceB faceB) {
    if(faceA != faceB) {
        throw new IllegalArgumentException();
    }

    // do some stuff with it
}

What would you suggest, what do you use / consider the best?

Was it helpful?

Solution

You would do

interface InterfaceAB extends InterfaceA, InterfaceB {}

And for an implementation

class SomeObject implements InterfaceAB {}

In reality if you have many subtype you usally have an abstract class that stores some common code. So you would have:

class AInterfaceAB implements InterfaceA, InterfaceB {}

So if you want to skip the container Interface you could use the abstract. Its not super elegant, but practical and has no real drawbacks, other than not using interface.

Different Approach: you could use generics with multiple upper bounds:

<T extends InterfaceA&InterfaceB> void doSomething(T argument) {
}

OTHER TIPS

How about this:

InterfaceA extends BaseAB

InterfaceB extends BaseAB

And BaseAB is an interface with EMPTY methods OR common methods.

You can use BaseAB in function like below:

void doSomething( BaseAB argument) {

      if (argument instanceof InterfaceA )
      { }
      else
      {}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top