有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用相同的方法和不同的返回类型实现多个接口的Java

考虑下面的代码:

public interface A {
  public A another();
}

public interface B {
  public B another();
}

public interface AB extends A,B {
  public AB another();
}

这会导致AB上出现编译错误:

types B and A are incompatible; both define another(), but with unrelated return types

我已经看到了这个SO question,并遵循了公认答案中的不兼容示例,即

public interface C { 
  public void doSomething();
}

public interface D {
  public boolean doSomething();
}

public interface CD extends C,D { 
}

然而,在这种情况下,返回类型实际上是不兼容的——返回类型不能同时是void和boolean。然而,在我上面的示例中,ABanother()返回类型既是A又是B,因此可以实现这两个扩展接口

此外,在看过JLS(8.4.8、8.4.8.3、8.4.8.4)之后,我不太明白为什么我上面的例子是非法的。谁能给我解释一下吗

第二,除了重复AB中的AB合同要求之外,还有其他解决方案/变通办法吗


共 (1) 个答案

  1. # 1 楼答案

    对于Java 1.5之前的版本,会出现此错误消息(至少在Eclipse中将遵从性级别设置为1.4时,我可以重现此错误)。换句话说,确保你看到的是足够古老的规格

    关于Java>;=1.5以下内容可供参考

    interface A {
        public A another();
    }
    
    interface B {
        public B another();
    }
    
    interface AB extends A,B {
        public AB another();
    }
    

    正如您所说,因为AB既是A又是B,所以它满足两个接口


    这里引用了Java语言规范(第二版,即Java 1.4):

    9.2 Interface Members

    The members of an interface are:

    • Those members declared in the interface.
    • Those members inherited from direct superinterfaces.
    • If an interface has no direct superinterfaces, [...]

    It follows that it is a compile-time error if the interface declares a method with the same signature and different return type or incompatible throws clause.

    此外,当前的规格说明如下:

    9.4.2 Overloading

    If two methods of an interface (whether both declared in the same interface, or both inherited by an interface, or one declared and one inherited) have the same name but different signatures that are not override-equivalent (§8.4.2), then the method name is said to be overloaded. This fact causes no difficulty and never of itself results in a compile-time error. There is no required relationship between the return types or between the throws clauses of two methods with the same name but different signatures that are not override-equivalent.