0

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?

4 Answers 4

7

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!

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

The method signature consists of the method's name and the parameters types, so you can't declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.

Comments

0

Think of a typical use for interfaces: e.g. 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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.