When calling supername method when overwriting a method?

5

In a class we have several methods overlapping with @Override , and in some, for example onPreExecute of an extended class of AsyncTask , already comes with super.onPreExecute() .

@Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

What would be this method super.nomeDoMetodo() and when to leave this call to the method of the upper class?

    
asked by anonymous 09.03.2018 / 11:49

2 answers

8

When writing a class that extends from another it is possible to override its methods.

In doing so you are writing another implementation, the original implementation being discarded / overwritten.

However, there are cases where, due to how the class was implemented, the original implementation of the overriding method must be performed.

The way to do this is to use super.nomeMetodoSobrescrito() .

When it is an abstract method, it is never necessary to do so. In other cases you should do so when the class documentation so indicates.

Regarding the Android SDK, at least in the use of the Activity class, an exception will be thrown if you do not. If, in Android Studio, using Generate ... - > Override Methods ... The method call will be automatically placed when it is needed.

    
09.03.2018 / 12:15
6

AsyncTask is an abstract class with some methods whose default implementation does nothing, including onPreExecute ().

These methods should be overridden (implemented) by AsyncTask subclasses.

That is, there is no default implementation of onPreExecute (). You do not need to call super.onPreExecute () because this call will do nothing. This holds true for some methods of the AsyncTask class.

There are situations where calling the super makes sense. This is (or at least should be) documented in the method or class Javadoc. For example, when overwriting Activity.onCreate (). In this case, there is already a default implementation in the superclass that must be complemented with the superscript method in the subclass.

"super" is a reference to the superclass. Just like "this" is a reference to the object itself. Calling method () is the same as calling this.method (), and calling super.method () will invoke the "parent" version of the method, that is, the implementation made in the superclass.

    
09.03.2018 / 12:17