Re: problem with method overloading
- From: ilan <ilan@xxxxxxxxxxxxxxxxxxxxx>
- Date: Mon, 14 Jun 2010 20:46:18 +0200
Lew <lew@xxxxxxxxxxxxx> writes:
Your method overload question is quite important, actually. It's a
common mistake to overload 'equals()' when the intent is to override,
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.
Simon Brooke wrote:
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
Yes. As I already stated in my post, it will fail in the general case
when clients invoke it with an 'Object' argument. You will then get
the non-overridden 'equals(Object)' method from the parent class,
which typically provides object identity comparison rather than value
comparison, or else value comparison on the wrong fields.
I can see how this might matter for other methods with different
semantics, but why equals, particularly?
The parent 'equals()' method typically is one of those "other methods
with different semantics". The semantics of 'equals(Object)' will
differ from that of 'equals(Foo)' without special care, i.e., an
override of the former that invokes the latter.
'equals()' is typically called with an 'Object' argument, and
therefore the overload will not be invoked. Things like collections
depend on the method to have an override. No override yields
Hmm.. So it should rather be?
public class Foo
public boolean equals( Object other )
Thanks! I just learnt something.