Search code examples
javaandroid-asynctask

What is the purpose of calling super class's method while overriding a method?


While overriding methods like onPostExecute from AsyncTask we can avoid or remove super.onPostExecute(result); from it. Can you tell me why and when do we need to use this call? as I here implemented AsyncTask as a inner class in my Main Activity

    private class CustomAsyncTask extends AsyncTask<String, Void, Event> {
    @Override
    protected Event doInBackground(String... strings) {
        Event result = Utils.fetchEarthquakeData(strings[0]);
        return result;
    }

    @Override
    protected void onPostExecute(Event result) {
        super.onPostExecute(result);// what is the effect of calling this? If it was possible to skip or remove it. 
        updateUi(result);
    }
    
}

Solution

  • When you override a method, you redefine the method i.e. if this method is called on the instance of the child class (in which you have overridden the method), this new version of the definition will be called.

    When you override a method (i.e. redefine or in other words, replace the superclass definition with the child's version of the definition), you have two choices:

    1. Do not use anything from the superclass definition and rewrite it in a completely new way.
    2. Reuse the superclass definition at some point (in the beginning/middle/end) in the new definition. It's like putting a cherry on the ice cream cone where ice cream cone is the superclass definition of the method and cherry is added in the new definition.

    Note that as already pointed out by Andy Turner, a requirement to call super is considered an antipattern.