Anti-pattern considerations aside, should I always call super
in Java when overriding methods, even when the method is empty?
Take a look at the code below, this is an excerpt from AsyncTask
and can be found here. AsyncTask
s are often used in Android and the only method we must implement is the abstract doInBackground()
. Other methods, such as onPreExecute()
and onPostExecute()
, are useful to override in some cases. Notice that these two methods are implemented but do not actually do anything, that is they are empty.
I’ve seen claims that because these are empty we do not have to override them. I still do because I do not know whether they’ll change it in a future implementation (and because the editor does it for me). Is there a best practice for this case?
/**
* Override this method to perform a computation on a background thread. The
* specified parameters are the parameters passed to {@link #execute}
* by the caller of this task.
*
* This method can call {@link #publishProgress} to publish updates
* on the UI thread.
*
* @param params The parameters of the task.
*
* @return A result, defined by the subclass of this task.
*
* @see #onPreExecute()
* @see #onPostExecute
* @see #publishProgress
*/
protected abstract Result doInBackground(Params... params);
/**
* Runs on the UI thread before {@link #doInBackground}.
*
* @see #onPostExecute
* @see #doInBackground
*/
protected void onPreExecute() {
}
/**
* <p>Runs on the UI thread after {@link #doInBackground}. The
* specified result is the value returned by {@link #doInBackground}.</p>
*
* <p>This method won't be invoked if the task was cancelled.</p>
*
* @param result The result of the operation computed by {@link #doInBackground}.
*
* @see #onPreExecute
* @see #doInBackground
* @see #onCancelled(Object)
*/
@SuppressWarnings({"UnusedDeclaration"})
protected void onPostExecute(Result result) {
}
1
I still do because I do not know whether they’ll change it in a future implementation (and because the editor does it for me).
A superclass that does this is a bad superclass. The superclass needs to tell you exactly what its implementation (if any) of the non-final
method does, under which circumstances it’ll be called by other superclass methods, and what you need to do to correctly override it.
Once it specifies these things, it can’t go back on them. Just like you need to maintain backwards compatibility of public
methods, superclasses need to maintain backwards compatibility of changes to inheritable methods or all hell breaks loose.