简体   繁体   中英

Java - Interfaces and methods

I'm looking through some interfaces at the moment and I'm wondering why this does not work:

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

Basically, why can't I implement the method in the interface? THey have different signatures as one has a return type? Isn't the name, parameters and return type what make a method unique?

You can't have different return types. Imagine the following

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!
}

Therefore, the return types must also be the same!

Yeah, you're basically correct. Java doesn't allow overloading methods by return type, which would be neat. However, the interface return type must still match.

方法签名由方法的名称和参数类型组成,因此您不能声明多个具有相同名称,相同数量和参数类型的方法,因为编译器无法区分它们。

Think of a typical use for interfaces: eg anything implementing the java List interface must implement boolean add(Object o)

The caller is probably going to do something like:

if (!impl.add(o)) { /* report error */ }

If you were allowed to change the return type, you'd hit all types of problems.

void add(Object o)
if (!impl.add(o)) { // ... your method returns void, so this makes no sense

float add(Object o)
if (!impl.add(o)) { // float to boolean ? are you sure that is what you meant?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM