I have a couple of interfaces:
public interface Speaker { void speak(); } public inteface Walker { void walk(); }
I want a method that takes instances that are both a Speaker
and a Walker
.
Now, I could implement another interface:
public interface WalkerSpeaker extends Walker, Speaker { }
And accept that:
void walkAndTalk(final WalkerSpeaker x) { x.walk(); x.speak(); }
But this is quite cumbersome with many combinations, and every implementation must inherit from WalkerSpeaker
for it to work!
Is there a better way?
So, if the class already has the same method as an Interface, then the default method from the implemented Interface does not take effect. However, if two interfaces implement the same default method, then there is a conflict.
An interface cannot implement another interface in Java. An interface in Java is essentially a special kind of class. Like classes, the interface contains methods and variables. Unlike classes, interfaces are always completely abstract.
Java does not support "multiple inheritance" (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below).
What would be the result if a class extends two interfaces and both have a method with same name and signature? Lets assume that the class is not implementing that method. Explanation: In case of such conflict, compiler will not be able to link a method call due to ambiguity. It will throw compile time error.
You can achieve this with generics as follows
public <T extends Speaker & Walker> void walkAndTalk(T x) { x.walk(); x.speak(); }
The type parameter T
will be "double-bounded" to both interfaces, so in essence T
will be a WalkerSpeaker
except you don't have to write a separate interface for it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With