• Post Reply Bookmark Topic Watch Topic
  • New Topic

what happens when a class implements two interfaces having same methods??  RSS feed

 
Aditya Anup
Greenhorn
Posts: 2
Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what happens when a class implements two interfaces having same methods??
 
umar farooque
Greenhorn
Posts: 4
Opera Pulse IDE Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when a class implements two interfaces having same methods create ambiguity error.
 
Rob Spoor
Sheriff
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the methods have the same name and argument types, you can only implement it once*. As far as the compiler is concerned, that's OK. Interface A requires you to implement the method, which you did. Interface A requires you to implement the method, which you did as well.

Now comes the tricky part. Although your implementation is syntactically correct, it may still fail semantically. The contract for interface A says that the method must do something. The contract for interface B says the method must do something. That may be a different something. Depending on what these two somethings are, you can either implement both in one method (satisfying the interface contracts both syntactically and semantically), or at most one. If the latter is the case (which would mostly be the case if the two contracts are contradicting) your class cannot implement both interfaces. There are techniques to bypass this though. One such way is to a method that return an implementation of interface A backed by the object itself, a method that return an implementation of interface B backed by the object itself, or both.


* Unless if the return types aren't covariant, then you have a conflict that you can't solve while still implementing the two interfaces.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!