Re: Ensuring a method is overridden
Mike Amling wrote:
I presume you recommend some kind of
proxy to ensure toString, equals, hashCode, etc. are overridden:
abstract class Basso {
protected abstract String abString();
public final String toString() {
return abString();
}
}
final class Extenso extends Basso {
public String abString() {
return "whatever";
}
}
That's sort of a strange suite of methods to require overriding. It's
already best practice to override toString, hashCode and equals,
though not "etc.". (What other methods of Object do you contemplate
overriding? Not much else makes sense to override.)
The pattern you show is a common one - define an abstract base class
with a public method that invokes abstract helper methods so that
subclasses can provide the varying parts. Often the abstract methods
are protected rather than public, since it's the wrapping method
(toString in your example) that you want client code to use, not the
helper method (abString).
Another approach is to define the desired methods completely in the
parent abstract class, not as abstract methods but with reasonable
behaviors so the child class doesn't really have to override but may.
That's the approach Object itself takes with these methods.
Another approach is to declare toString and the others abstract in
your base class.
<sscce>
package eegee;
abstract class AbstractOver
{
@Override abstract public String toString();
}
public class ForceOver extends AbstractOver
{
@Override public String toString()
{
return getClass().getName();
}
}
</sscce>
--
Lew