Java - Method name collision in interface implementation

前端 未结 7 1442
渐次进展
渐次进展 2020-11-22 13:23

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 sin

7条回答
  •  执念已碎
    2020-11-22 13:41

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

提交回复
热议问题