开发者

Type of class which implements multiple interfaces

开发者 https://www.devze.com 2023-03-14 22:36 出处:网络
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

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();
}

An开发者_运维技巧d 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();


Do a new interface

public interface IAandB extends IA, IB 

and make FooA and FooB implement it instead.


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{...}


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();


If there is the possibility that a class implementes IA and IB, and this fact makes conceptually sense for the problem domain you're working in, the just have a IAB like this

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

Do determine if it makes sense in your case might be as simple as asking yourself what would be a good name for IAB? If you can come up with a satisfactory answer to this, you can just add that interface. If not, then the right place for your two

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

lines would be a method of FooA or FooB (or an base class of these two). This way you don't have to make casts or guesses about the nature of the classes that implement your interfaces (which might become invalid or troublesome to handle later).

0

精彩评论

暂无评论...
验证码 换一张
取 消