Re: problem with method overloading
On 14-06-2010 13:46, Simon Brooke wrote:
On Mon, 14 Jun 2010 10:05:08 -0700, Lew wrote:
Your method overload question is quite important, actually. It's a
common mistake to overload 'equals()' when the intent is to override,
e.g.,
public class Foo
{
...
public boolean equals( Foo other )
{
...
}
}
This method will appear to work if passed a 'Foo' argument because the
'Foo' argument matches more specifically than the 'Object' argument to
the other 'equals()' method in the class, but it will fail in general
when clients pass an 'Object' argument and bypass the specific overload,
getting the parent-class version instead.
Sorry, why is this a mistake? If a 'Bar' argument is passed, equals must
return false anyway. Does it matter which implementation of equals is
invoked?
I can see how this might matter for other methods with different
semantics, but why equals, particularly?
equals(Object) is more polymorh than equals(Foo) !
Try and run this little demo:
public class Equals {
public static void main(String[] args) {
Foo foo1 = new Foo(123);
Foo foo2 = new Foo(123);
System.out.println(foo1.equals(foo2));
Object ofoo1 = new Foo(123);
Object ofoo2 = new Foo(123);
System.out.println(ofoo1.equals(ofoo2));
Bar bar1 = new Bar(123);
Bar bar2 = new Bar(123);
System.out.println(bar1.equals(bar2));
Object obar1 = new Bar(123);
Object obar2 = new Bar(123);
System.out.println(obar1.equals(obar2));
}
}
class Foo {
private int v;
public Foo(int v) {
this.v = v;
}
public boolean equals(Foo o) {
return (v == o.v);
}
public int hashCode() {
return v;
}
}
class Bar {
private int v;
public Bar(int v) {
this.v = v;
}
@Override
public boolean equals(Object o) {
return (o instanceof Bar) && (v == ((Bar)o).v);
}
@Override
public int hashCode() {
return v;
}
}
The Bar class works as expected with polymorphism. The Foo class
gives inconsistent results depending on the type of the reference.
Arne