92

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 ?

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Bhaskar
  • 7,443
  • 5
  • 39
  • 51
  • 39
    When *one* class has to implement two methods with the same signature that do *different things*, then your class is **almost certainly** doing too many things. – Joachim Sauer Apr 08 '10 at 06:45
  • 15
    The above may not true always IMO.Sometimes , in a single class , you need methods that must confirm to an external contract ( thus constraining on the signatures ) , but which have different implementations. In fact , these are common requirements when designing a non-trivial class. Overloading and overriding are necessarily mechanisms to allow for methods that do different things that may not differ in signature , or differ very slightly.What I have here is just a bit more restrictive in it that it does not allow subclassing / and does not allow even slightest variation on signatures. – Bhaskar Apr 08 '10 at 13:07
  • 1
    I'd be intrigued to know what these classes and methods are. – Uri Apr 08 '10 at 14:04
  • 2
    I encountered such a case where a legacy "Address" class implemented Person and Firm interfaces that had a getName() method simply returning a String from the data model. A new business requirement specified that the the Person.getName() return a String formatted as "Surname, Given names". After much discussion, the data was re-formated in the database instead. – belwood Jan 10 '12 at 18:13
  • 13
    Just stating that the class is almost certainly doing too many things is NOT CONSTRUCTIVE. I've got this very case right now that my class has mehod name collisions from 2 different interfaces, and my class is NOT doing too many things. The purposes are quite similar, but do slightly different things. Don't try to defend a obviously severely handicapped programming language by accusing the questioner of implementing bad software design! – j00hi Jul 22 '14 at 10:29
  • `doing too many things` is a BS excuse. I have an `interface Nameable { String name(); }` and want an `enum` that implements that interface. Unfortunately `Enum`s define their own, `final` (that's understandable) `name()` method, leaving me with no option but to implement this as a class. How stupid is that?! C# solved this 15 years ago. – Sebastian Graf Nov 19 '16 at 11:41
  • @j00hi If you know of other programming languages that handle this scenario more gracefully, could you share an example? – nishanthshanmugham Oct 26 '17 at 05:10
  • 1
    @nishanths Already the OP mentioned C# which achieves that by "explicit interface implementation". Here is an example of a class implementing two interfaces `SampleClass : IControl, ISurface`, each defining a `Paint` method: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/interfaces/explicit-interface-implementation – j00hi Oct 27 '17 at 07:33
  • I came across this because I was hoping to to make things easier for some AOP based metrics annotations that use method name, so I could name the method something descriptive and then name the interface method something generic to allow for polymorphism and keep the AOP metrics stuff. – joezen777 May 07 '19 at 13:47

7 Answers7

78

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();}
}
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
jjnguy
  • 136,852
  • 53
  • 295
  • 323
  • 10
    But this way , I cannot pass an instance of CompositeClass somewhere a reference of the interfaces ( ISomething or ISomething2 ) are expected ? I cannot even expect client code to be able to cast my instance to the appropriate interface , so am I not loosing something by this restriction ? Also note that in this way , when writing classes that actually implement the respective interfaces , we loose the benefit of having the code into a single class , which may be a serious impediment sometimes. – Bhaskar Apr 08 '10 at 09:18
  • 10
    @Bhaskar, you make valid points. The best advice I have is add a `ISomething1 CompositeClass.asInterface1();` and `ISomething2 CompositeClass.asInterface2();` method to that class. Then you can just get one or the other out of the composite class. There is no great solution to this problem though. – jjnguy Apr 08 '10 at 09:30
  • 1
    Speaking of the confusing situations this can lead to , can you give an example ? Can we not think of the interface name added to the method name as an extra scope resolution which can then avoid the collision/ confusion ? – Bhaskar Apr 08 '10 at 10:18
  • @Bhaskar Its better if our classes adhere to single responsibility principle. If there exists a class that implements two very different interfaces i think the design should be reworked to split the classes to take care of single responsibility. – Anirudhan J Nov 08 '13 at 17:02
  • 1
    How confusing would it be, really, to allow something like `public long getCountAsLong() implements interface2.getCount {...}` [in case the interface requires a `long` but users of the class expect `int`] or `private void AddStub(T newObj) implements coolectionInterface.Add` [assuming `collectionInterface` has a `canAdd()` method, and for all instances of this class it returns `false`]? – supercat Dec 17 '13 at 22:55
  • _"That can lead to many confusing situations"_ -- please elaborate. I've never found this to be a problem in C# and really miss it occasionally in Java. Ultimately it's straightforward to reason about which interface implementation will be called when the implementation is explicit. – Drew Noakes Aug 27 '14 at 19:54
  • What occurs if we have two methods in the interfaces with different return types? So a ```String doSomething();``` in one interface and a ```double doSomething();``` in another interface. Which guy gets implemented? – Dude156 Oct 15 '20 at 02:00
  • 1
    @supercat very confusing, obviously. I can’t even read that comment… – Holger Oct 25 '21 at 16:35
14

There's no real way to solve this in Java. You could use inner classes as a workaround:

interface Alfa { void m(); }
interface Beta { void m(); }
class AlfaBeta implements Alfa {
    private int value;
    public void m() { ++value; } // Alfa.m()
    public Beta asBeta() {
        return new Beta(){
            public void m() { --value; } // Beta.m()
        };
    }
}

Although it doesn't allow for casts from AlfaBeta to Beta, downcasts are generally evil, and if it can be expected that an Alfa instance often has a Beta aspect, too, and for some reason (usually optimization is the only valid reason) you want to be able to convert it to Beta, you could make a sub-interface of Alfa with Beta asBeta() in it.

gustafc
  • 28,465
  • 7
  • 73
  • 99
  • Do you mean anonymous class rather than inner class? – Zaid Masud Sep 07 '12 at 13:39
  • 2
    @ZaidMasud I mean inner classes, since they can access the private state of the enclosing object). These inner classes can of course be anonymous, too. – gustafc Sep 07 '12 at 14:13
13

If you are encountering this problem, it is most likely because you are using inheritance where you should be using delegation. If you need to provide two different, albeit similar, interfaces for the same underlying model of data, then you should use a view to cheaply provide access to the data using some other interface.

To give a concrete example for the latter case, suppose you want to implement both Collection and MyCollection (which does not inherit from Collection and has an incompatible interface). You could provide a Collection getCollectionView() and MyCollection getMyCollectionView() functions which provide a light-weight implementation of Collection and MyCollection, using the same underlying data.

For the former case... suppose you really want an array of integers and an array of strings. Instead of inheriting from both List<Integer> and List<String>, you should have one member of type List<Integer> and another member of type List<String>, and refer to those members, rather than try to inherit from both. Even if you only needed a list of integers, it is better to use composition/delegation over inheritance in this case.

avojak
  • 2,342
  • 2
  • 26
  • 32
Michael Aaron Safyan
  • 93,612
  • 16
  • 138
  • 200
  • I don't think so. You're forgetting libraries that require you to implement different interfaces to be compatible with them. You can run into this by using multiple conflicting libraries a lot more often then you run into this in your own code. – nightpool Feb 20 '16 at 21:45
  • 3
    @nightpool if you use multiple libraries that each require different interfaces, it is still not necessary for a single object to implement both interfaces; you can have the object have accessors for returning each of the two different interfaces (and call the appropriate accessor when passing along the object to one of the underlying libraries). – Michael Aaron Safyan Feb 22 '16 at 04:24
2

The only solution that came in my mind is using referece objects to the one you want to implent muliple interfaceces.

eg: supposing you have 2 interfaces to implement

public interface Framework1Interface {

    void method(Object o);
}

and

public interface Framework2Interface {
    void method(Object o);
}

you can enclose them in to two Facador objects:

public class Facador1 implements Framework1Interface {

    private final ObjectToUse reference;

    public static Framework1Interface Create(ObjectToUse ref) {
        return new Facador1(ref);
    }

    private Facador1(ObjectToUse refObject) {
        this.reference = refObject;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof Framework1Interface) {
            return this == obj;
        } else if (obj instanceof ObjectToUse) {
            return reference == obj;
        }
        return super.equals(obj);
    }

    @Override
    public void method(Object o) {
        reference.methodForFrameWork1(o);
    }
}

and

public class Facador2 implements Framework2Interface {

    private final ObjectToUse reference;

    public static Framework2Interface Create(ObjectToUse ref) {
        return new Facador2(ref);
    }

    private Facador2(ObjectToUse refObject) {
        this.reference = refObject;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof Framework2Interface) {
            return this == obj;
        } else if (obj instanceof ObjectToUse) {
            return reference == obj;
        }
        return super.equals(obj);
    }

    @Override
    public void method(Object o) {
        reference.methodForFrameWork2(o);
    }
}

In the end the class you wanted should something like

public class ObjectToUse {

    private Framework1Interface facFramework1Interface;
    private Framework2Interface facFramework2Interface;

    public ObjectToUse() {
    }

    public Framework1Interface getAsFramework1Interface() {
        if (facFramework1Interface == null) {
            facFramework1Interface = Facador1.Create(this);
        }
        return facFramework1Interface;
    }

    public Framework2Interface getAsFramework2Interface() {
        if (facFramework2Interface == null) {
            facFramework2Interface = Facador2.Create(this);
        }
        return facFramework2Interface;
    }

    public void methodForFrameWork1(Object o) {
    }

    public void methodForFrameWork2(Object o) {
    }
}

you can now use the getAs* methods to "expose" your class

notAtAll
  • 21
  • 1
1

The "classical" Java problem also affects my Android development...
The reason seems to be simple:
More frameworks/libraries you have to use, more easily things can be out of control...

In my case, I have a BootStrapperApp class inherited from android.app.Application,
whereas the same class should also implement a Platform interface of a MVVM framework in order to get integrated.
Method collision occurred on a getString() method, which is announced by both interfaces and should have differenet implementation in different contexts.
The workaround (ugly..IMO) is using an inner class to implement all Platform methods, just because of one minor method signature conflict...in some case, such borrowed method is even not used at all (but affected major design semantics).
I tend to agree C#-style explicit context/namespace indication is helpful.

tiancheng
  • 21
  • 3
  • 1
    I never realised how C# was thoughtful and feature-rich until I started using Java for Android development. I took those C# features for granted. Java lacks too many features. – Damn Vegetables Jul 07 '16 at 16:33
0

You can use an Adapter pattern in order to make these work. Create two adapter for each interface and use that. It should solve the problem.

AlexCon
  • 1,127
  • 1
  • 13
  • 31
-1

All well and good when you have total control over all of the code in question and can implement this upfront. Now imagine you have an existing public class used in many places with a method

public class MyClass{

    private String name;

    MyClass(String name){
        this.name = name;
    }

    public String getName(){
        return name;
    }
}

Now you need to pass it into the off the shelf WizzBangProcessor which requires classes to implement the WBPInterface... which also has a getName() method, but instead of your concrete implementation, this interface expects the method to return the name of a type of Wizz Bang Processing.

In C# it would be a trvial

public class MyClass : WBPInterface{

    private String name;

    String WBPInterface.getName(){
        return "MyWizzBangProcessor";
    }

    MyClass(String name){
        this.name = name;
    }

    public String getName(){
        return name;
    }
}

In Java Tough you are going to have to identify every point in the existing deployed code base where you need to convert from one interface to the other. Sure the WizzBangProcessor company should have used getWizzBangProcessName(), but they are developers too. In their context getName was fine. Actually, outside of Java, most other OO based languages support this. Java is rare in forcing all interfaces to be implemented with the same method NAME.

Most other languages have a compiler that is more than happy to take an instruction to say "this method in this class which matches the signature of this method in this implemented interface is it's implementation". After all the whole point of defining interfaces is to allow the definition to be abstracted from the implementation. (Don't even get me started on having default methods in Interfaces in Java, let alone default overriding.... because sure, every component designed for a road car should be able to get slammed into a flying car and just work - hey they are both cars... I'm sure the the default functionality of say your sat nav will not be affected with default pitch and roll inputs, because cars only yaw!