Java - 接口和方法

Tim*_*Tim 0 java methods interface

我正在浏览一些接口,我想知道为什么这不起作用:

interface I {
    public void doSomething(String x);
}
class MyType implements I {
    public int doSomething(String x) {
        System.out.println(x);
        return(0); 
    }
}
Run Code Online (Sandbox Code Playgroud)

基本上,为什么我不能在界面中实现该方法?有一个返回类型有不同的签名吗?是不是名称,参数和返回类型使方法独特?

Gwy*_*ell 7

您不能拥有不同的退货类型.想象一下以下内容

class Foo implements I {
  public int doSomething(String x) {
    System.out.println(x);
    return(0);
  }
}
class Bar implements I {
  public void doSomething(String x) {
    System.out.println(x);
    return;
  }
}

List<I> l = new ArrayList();
l.add(new Foo());
l.add(new Bar());

for (I i : l) {
  int x = i.doSomething();  // this makes no sense for Bar!
}
Run Code Online (Sandbox Code Playgroud)

因此,返回类型也必须相同!