Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a method accept instances with two interfaces? [duplicate]

Tags:

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?

like image 820
sdgfsdh Avatar asked Jun 15 '16 13:06

sdgfsdh


People also ask

CAN 2 interfaces have same method?

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.

Can we implement an interface twice?

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.

Can you use two interfaces at once in Java?

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 class extends two interfaces and both have method with same name and signature?

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.


1 Answers

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.

like image 121
Kayaman Avatar answered Sep 19 '22 21:09

Kayaman