This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

multiple interfaces  RSS feed

 
Franny N. Zooey
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can a class implement two interfaces that each contains the same method signature?
Franny
 
David Crossett
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My guess is no, as the compiler won't be able to figure out which method needs to be called. All methods must have unique signatures. That's just a guess, though. You must be implementing custom interfaces?
 
Joe Ess
Bartender
Posts: 9429
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by David Crossett:
My guess is no

Your guess is wrong. Try compiling this:

An interface is just a contract. A class that implements a method is saying that it will provide a methods with the signitures that the interface specifies. Since interfaces can't have method bodies, there's really no problem implementing two interfaces with the same method signiture. The class is fulfilling its part of the contract by implementing the method the two interfaces declare.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually you can implement two such interfaces. This doesn't mean you'll be able to do so sensibly since, as David points out, the object will have no idea which interfaces's foo() method is being called, so one implementation will have to, somehow, serve both.
The JLS has some specific language addressing this, including what happens if the two method declarations in the interfaces have different exception specifiers (the implementing method has to be able to satisfy both declarations at once.)
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!