Android methods override

When we redefine a method in a subclass, we call the superclass method in this method, for example:

protected void onSizeChanged(int w, int h, int oldw, int oldh) { width = w ; height = h ; Log.d(TAG, "onSizeChanged: width " + width + ", height "+ height); super.onSizeChanged(w, h, oldw, oldh); } 

So why do we need to call super.onSizeChanged() ?

I delete the line super.onSizeChanged() and the result will be the same as with it.

Or the same in the onCreate method, we call super.onCreate() .

+6
source share
4 answers

There are certain methods that do important things, such as onCreate and onPause activity methods. If you override them without calling the super method, this will not happen and the action will not work properly. In other cases (usually when implementing an interface) there is no implementation that you override, only declarations and, therefore, there is no need to call the super method.

One more thing, sometimes you override a method, and your goal is to change the behavior of the original method, not extend it. In such cases, you should not call the ssuper method. An example of this is the method of drawing swing components.

+1
source

In object-oriented programming, users can inherit the properties and behavior of a superclass in subclasses. A subclass can override the methods of its superclass, replacing its own implementation of the method for implementing the superclass.

Sometimes the overriding method completely replaces the corresponding functionality in the superclass, while in other cases the superclass method still needs to be called from the override method. Therefore, most programming languages ​​require that an overriding method must explicitly call an overridden method on superclasses to execute it.

+2
source

For some method, you must call a super method to initialize some object or variable (otherwise you will get a supernova exception), for others you can call it, but you noticed.

+1
source

There are many things that the Android API will do in the onCreate (or any other on_ ____ ) method of the Activity class.

Now, when you redefine a method, your implementation will be used instead of the one that is in the activity class during the execution of this operation, since this means that it is an override. It overrides the implementation of the parent (i.e. the Activity class) and replaces it with the child implementation (i.e. your class).

So, Android applies this rule, which you always need to call the parent implementation in addition to your own implementation, so that the parent implementation (containing many important things) remains intact in addition to your implementation.

I hope this is thorough and clear enough.

0
source

Source: https://habr.com/ru/post/893994/


All Articles