且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java - 接口实现中的方法名称冲突

更新时间:2022-12-04 23:24:45

不,没有办法在 Java 的一个类中以两种不同的方式实现相同的方法.

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

这会导致许多令人困惑的情况,这就是 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();}
}