Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Method name collision in interface implementation

If I have two interfaces , both quite different in their purposes , but with same method signature , how do I make a class implement both without being forced to write a single method that serves for the both the interfaces and writing some convoluted logic in the method implementation that checks for which type of object the call is being made and invoke proper code ?

In C# , this is overcome by what is called as explicit interface implementation. Is there any equivalent way in Java ?

like image 722
Bhaskar Avatar asked Apr 08 '10 06:04

Bhaskar


People also ask

What is naming conflicts in Java?

Naming Conflicts occur when a class implements two interfaces that have methods and variables with the same name.

Can you have a class and an interface with the same name Java?

You can't have a class and an interface with the same name because the Java language doesn't allow it.

CAN interface have data members in Java?

It cannot have a method body. Java Interface also represents the IS-A relationship. Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body).

WHAT IS interface in Java with example?

An interface in Java is a blueprint of a class. It has static constants and abstract methods. The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.


1 Answers

No, there is no way to implement the same method in two different ways in one class in Java.

That can lead to many confusing situations, which is why Java has disallowed it.

interface ISomething {     void doSomething(); }  interface ISomething2 {     void doSomething(); }  class Impl implements ISomething, ISomething2 {    void doSomething() {} // There can only be one implementation of this method. } 

What you can do is compose a class out of two classes that each implement a different interface. Then that one class will have the behavior of both interfaces.

class CompositeClass {     ISomething class1;     ISomething2 class2;     void doSomething1(){class1.doSomething();}     void doSomething2(){class2.doSomething();} } 
like image 134
jjnguy Avatar answered Sep 20 '22 17:09

jjnguy