This code works perfectly. The method test() works for both interfaces. What is exactly going on under the hood? And how is this feature useful in practical scenario?
interface A
{
void test();
}
interface B
{
void test();
}
class C implements A, B
{
public void test()
{
System.out.println("abc");
}
}
A a = new C();
a.test();
B b = new C();
b.test();
Not as far as syntax is concerned but if the
intent
of one of themethods
is not adhered to, its contract is broken and the code can be considered as broken.Using your analogy, if I promised Michael to wear a blue shirt instead of a red shirt, and I can't wear two shirts, then I will have to break at least one promise.
The same can hold for the methods: if keeping one contract would mean breaking the other then it's in fact a bad idea to
implement
bothinterfaces
.Edit:Contract broken, As per
Class C signature
It should implement two methods,but ultimately its implementing only onemethod
and omitting another.Reference
Because it's an interface there is no harm done. You're basically using a blueprint for your
C
class by implementingA
andB
. BothA
andB
say thatC
should implement a method calledtest()
Your
C
class implements that method, so the interfaces have done their job.It's basically your
C
class saying: "Oh hey, I need to implementtest()
because of interfaceA
" and you implement it. Then yourC
class says "Oh hey, I need to implementtest()
again because of interfaceB
" and it sees that there is already a method calledtest()
implemented so it's satisfied.You can also find more information here: JLS §8.4.8.4
Suppose we have two interfaces...
And a class implementing both interfaces....
While it may be syntactically correct to implement both interfaces with one method, you may not get the desired behavior. For example, a stock broker and a doctor typically each give their clients vastly different advice.
Someone using an object that implements the interface
Doctor
expects theadviseClient()
method to give medical advice. But someone using an object that implements the interfaceStockBroker
expects theadviseClient()
method to give out investment strategies.In this case, the object
JackOfAllTrades
does not know what type of advice to give out because theadviseClient()
method has no parameters telling it which interface it is supposed to be implementing whenadviseClient()
is called.This is a shortcoming in Java because the person designing the
Doctor
interface may have had no way of knowing that someone else would design aStockBroker
interface with the same method signature.To anyone creating interfaces, its probably good practice to make the method names unique enough that name collisions are rare.
JLS §8.4.8.4 says,
It seems the rationale was that if a class has multiple declarations with the same name and signature, since the class may have inherited them through multiple paths—implementing an interface and also subclassing a class that implements that interface, for example—no harm is done.