Java - Method name collision in interface implementation Java - Method name collision in interface implementation java java

Java - Method name collision in interface implementation


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();}}


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.


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.