Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type of class which implements multiple interfaces

Tags:

java

interface

I'm currently trying to write some classes and I come accross the following problem:

I'm trying to write a class that implements some functionality from two interfaces

interface IA {
 public void doSomething();
}

interface IB {
 public void doSomethingToo();
}

And I have two classes implementing those interfaces:

class FooA implements IA, IB{

}

class FooB implements IA, IB{

}

Is there I way I can do this:

public <type> thisClassImGonnaUse = returnEitherFooAOrFooB();
thisClassImGonnaUse.doSomething();
thisClassImGonnaUse.doSomethingToo();
like image 777
Timo Willemsen Avatar asked Jun 22 '11 19:06

Timo Willemsen


3 Answers

Do a new interface

public interface IAandB extends IA, IB 

and make FooA and FooB implement it instead.

like image 126
jontro Avatar answered Nov 03 '22 08:11

jontro


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

abstract class Base implements IA, IB{}

and

class FooA extends Base implements IA, IB{...}
like image 26
Bala R Avatar answered Nov 03 '22 09:11

Bala R


This might not be exactly what you want, but you could make a 3rd interface that extends both of them:

interface IAandB extends A, B {}

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

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

Then you can declare thisClassImGonnaUse to be of type IAandB:

public IAandB thisClassImGonnaUse = returnEitherFooAorFooB();
thisClassImGonnaUse.doSomething();
thisClassImGonnaUse.doSomethingToo();
like image 33
Michael McGowan Avatar answered Nov 03 '22 09:11

Michael McGowan