Java Reference
In-Depth Information
return false;
Name n = (Name)o;
return n.first.equals(first) && n.last.equals(last);
}
To make the program work, you merely have to add the overriding equals method. You don't have
to eliminate the overloaded one, but you are better off without it. Overloadings represent
opportunities for error and confusion [EJ Item 26]. If compatibility dictates that you must retain a
"self-typed" equals method, implement the Object overloading in terms of the self-typed
overloading to ensure identical behavior:
public boolean equals(Object o) {
return o instanceof Name && equals((Name) o);
}
The lesson of this puzzle is: Don't overload a method when you want to override. To avoid
unintentional overloading, mechanically copy the declaration of each superclass method that
you want to override , or better yet, let your IDE do it for you. Besides protecting you against
unintentional overloading, this protects you against misspelling method names. If you are using
release 5.0 or a later release, apply the @Override annotation to each method declaration that is
intended to override a superclass method:
@Override public boolean equals(Object o) { ... }
With this annotation, the program will not compile unless the annotated method overrides a
superclass method. For language designers, it is worth considering a mandatory modifier on each
method declaration that overrides a superclass method.
< Day Day Up >
 
 
Search WWH ::




Custom Search