具有相同方法名称的两个接口 - 方法的实现

Two Interface with Same Method Name - Implementation of Methods

假设我有两个接口:

interface IOne {

    public void method();

}

interface ITwo {

    public void method();

}

具体 class 实现了两个接口:

public class A implements IOne, ITwo {

    public void method(){
       //some implementation
    }
}

我的问题是:

  1. method() 的单一实现是否满足 IOne 和 ITwo 接口?
  2. 如果1的答案是肯定的,有没有办法在一个class中同时获得这两种方法?在这种情况下,我们不必在单个 class.
  3. 中实现两个接口
  1. 是的。当 class 作为 IOneITwo.

    的实例访问时,将调用该方法
  2. 没有。方法的名称、return 类型和参数定义了方法的签名,同一 class 中的两个方法不能具有相同的签名。这样做会导致编译时错误。

    我建议的一个解决方案是为 IOne.method 和 ITwo.method 使用不同的方法名称,从而使每个方法的签名都是唯一的。这将允许您在单个 class.

    中定义两个独特的方法

Does the single implementation of method() one suffice for both interface IOne and ITwo?

是的。 abstract 方法的实现是相同的。

If the answer of 1 is yes, is there any way to get both the method in a single class?

没有

如果两种方法具有相同的签名,就像您的示例中的情况一样,只有一种实现是可能的。在这种情况下,没有办法为两个接口实现两个版本的方法。所以是的,这个例子就足够了。

如果两个方法的签名相同,但它们具有不同的return类型,这将导致编译错误。

如果这两个方法具有不同的签名,则可以而且必须有两个不同的实现。

对于 1,答案是。为class中的方法提供一个实现就可以自动实现两个接口。

对于 2,如果您需要同时拥有这两种方法,那么您的 class 不应实现这两种接口。但是,您可以使用一个技巧:

interface IOne {

    void method();
}

interface ITwo {

    void method();
}

public class A
    implements IOne, ITwo {

    // Anonymous inner class that implements ony IOne
    private final IOne one = new IOne() {

        @Override
        public void method() {
            System.out.println("IOne");
        }
    };

    // Anonymous inner class that implements ony ITwo
    private final ITwo two = new ITwo() {

        @Override
        public void method() {
            System.out.println("ITwo");
        }
    };

    @Override
    public void method() {
        System.out.println("A");
    }

    // Method that delegates to IOne
    public void methodIOne() {
        this.one.method();
    }

    // Method that delegates to ITwo
    public void methodITwo() {
        this.two.method();
    }
}

测试代码:

A a = new A();
a.method(); // A
a.methodIOne(); // IOne
a.methodITwo(); // ITwo

Class A 不需要实现这两个接口。在那种情况下,不要在 A 上实现 method() 并只保留匿名内部 classes.