Tim
Tim

Reputation: 1074

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?

Upvotes: 0

Views: 103

Answers (4)

jalopaba
jalopaba

Reputation: 8119

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.

Upvotes: 1

John3136
John3136

Reputation: 29266

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?

Upvotes: 0

Gwyn Howell
Gwyn Howell

Reputation: 5424

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!

Upvotes: 7

Nick Martin
Nick Martin

Reputation: 282

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.

Upvotes: 2

Related Questions