开发者

interface implementation confusion?

I see a code where there are two interfaces having some methods with two methods having same name. Then there is a class that implements these interfaces i think it should not have compiled because of ambiguity in method names. 开发者_运维问答Why does it works fine.


Every language in which this problem can occur will solve the problem differently. In some languages, this can be an error; C++ is this way. But in Java, as long as the two methods have compatible exception specifications -- i.e., as long as it's actually possible to implement a method that satisfies both interfaces -- then it's specifically allowed by the language spec. The one method satisfies each interface, and everything is fine. It's meaningless to ask which interface the method belongs to; it belongs to both, or to none.

Note that you can have a class with a method x(), and then extend that class with a child class that declares itself to implement some interface that includes a method x(); the child automatically satisfies the interface using the inherited method, which itself was declared with no knowledge whatsoever of the interface. As you can see, Java interfaces are purely declarative; they don't care where the method comes from, only that the class in question includes them.

I can't speak for PHP, but perhaps it's just the same, but I'm sure it differs in some of the small details.


There is no ambiguity in method names if the methods are the same.

So, in essence, there is no problem in Java since the implementing class should provide only one implementation.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜