joy
joy

Reputation: 741

Are methods overridden when methods have the same name but different signatures?

public class Superclass {

   void method(Object a){
   }
}


public class Subclass extends Superclass {

    void method(String a){
    }
}

In the class above, method in Superclass has parameter of type Object while Subclass has parameter of type String. String is the subclass of Object. My question is, is method overriden in this case?

Upvotes: 3

Views: 3849

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200168

The most famous example of confusion caused by the issue you raise involves equals:

public class Banana {
  private final double weight;
  public boolean equals(Banana that) { return this.weight == that.weight; }
}

Many people think this is a valid override of equals, but it's actually just another method unrelated to Object#equals(Object) and will not be involved in equals comparison.

This is one of known pitfalls of Java's type system so take good care to get it right.

To confuse matters further, you are allowed to specialize the return type (the return type is covariant):

public abstract class FruitTree {
  public abstract Object getFruit();
}
public class BananaTree {
  ...
  @Override public Banana getFruit() { return this.bananas.iterator().next(); }
}

Note that the notion of method signature does not include the return type. Method signature is the key concept in the mechanism of static (compile-time) method resolution, and each signature is a separate point of dynamic method dispatch.

Upvotes: 4

codeMan
codeMan

Reputation: 5758

No, its method overloading. For it to be the method overriding the method signature of the super class method and subclass method should be same. Go through this blog post to know about these two and their difference in detail

Upvotes: 7

Related Questions