A type of class that implements multiple interfaces.

I am currently trying to write several classes, and I am facing the following problem:

I am trying to write a class that implements some functions from two interfaces

interface IA { public void doSomething(); } interface IB { public void doSomethingToo(); } 

And I have two classes implementing these interfaces:

 class FooA implements IA, IB{ } class FooB implements IA, IB{ } 

Is there a way I can do this:

 public <type> thisClassImGonnaUse = returnEitherFooAOrFooB(); thisClassImGonnaUse.doSomething(); thisClassImGonnaUse.doSomethingToo(); 
+8
java interface
source share
4 answers

Make a new interface

 public interface IAandB extends IA, IB 

and do FooA and FooB instead.

+9
source share

you can create an abstract base class or other interface that extends both IA and IB

 abstract class Base implements IA, IB{} 

and

 class FooA extends Base implements IA, IB{...} 
+1
source share

It may not be exactly what you want, but you can make a third interface that extends both of them:

 interface IAandB extends A, B {} 

Then FooA and FooB will implement IAandB instead of IA and IB directly:

 class FooA implements IAandB{} class FooB implements IAandB{} 

You can then declare thisClassImGonnaUse type IAandB :

 public IAandB thisClassImGonnaUse = returnEitherFooAorFooB(); thisClassImGonnaUse.doSomething(); thisClassImGonnaUse.doSomethingToo(); 
+1
source share

If it is likely that the class implements IA and IB , and this fact makes conceptual sense for the problem area in which you are working, just use IAB , like this

 interface IAB extends IA, IB { /* nothing */ } 

Determine if it makes sense in your case, it can be as simple as asking yourself what would be a good name for IAB? If you can find a satisfactory answer to this question, you can simply add this interface. If not, then the right place for your two

 thisClassImGonnaUse.doSomething(); thisClassImGonnaUse.doSomethingToo(); 

is the FooA or FooB (or the base class of the two). This way, you don’t need to take any action or guess about the nature of the classes that implement your interfaces (which may become invalid or difficult to process later).

0
source share

All Articles