• Post Reply Bookmark Topic Watch Topic
  • New Topic

Two interfaces specify methods with the same signature, but specified to have different behavior?  RSS feed

 
SuvenduSekhar Panda
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have some class public class myClass implements A, B where A and B both contain a method public int doSomething();, but A.doSomething is specified by the interface to do something different than B.doSomething.

I have read Two interfaces with same method signature implemented in Java class, but that doesn't really address my problem, because the methods are overriden to do the same thing, but as I said above, my question is about when they are specified in the interfaces to do different things.

For example, suppose A.doSomething() is supposed to return 0, while B.doSomething() is supposed to throw an exception, and violating either one wold cause problems for methods that are supposed to take them as parameters.

Is there any way to do this in java?
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, fundamentally you're a victim of a bad design, and the best solution is to overthrow the person who put you in this situation.

In theory, if the two doSomething methods had requirements that were orthogonal, not incompatible, you could do both in the implementing method, and satisfy both requirements.

In the example you give, the requirements are completely incompatible, and there is no way to implement this in Java, period. Or in any other programming language I'm aware of. Perhaps using some sort of quantum computing.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are languages where you can do this - e.g. in C# you can explicitly state the interface that you are implementing the method from. But I'd avoid using that feature whenever possible because it can lead to confusion - the version that is called depends on the reference type of the variable used to call it.

But no, it's not possible to do this in Java, so you really need to change the design. If you have control over the interfaces, it's probably easiest to change one so that the method is different. If you don't then you can't have a single object implementing both interfaces if they are incompatible (without breaking one of the contracts). If you don't want to use two entirely distinct objects, one suggestion would be to implement one of them, and then use a wrapper for that object that implements the second (a bit like the Adapter pattern).
 
SuvenduSekhar Panda
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank You all for replying...
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!