When we override a method in a subclass, we call the superclass method within 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 is the same as with it.
Or the same in onCreate method, we call super.onCreate()
.
In Java, method overriding occurs when a subclass (child class) has the same method as the parent class. In other words, method overriding occurs when a subclass provides a particular implementation of a method declared by one of its parent classes.
Example 1: Method OverridingWhen we call displayInfo() using the d1 object (object of the subclass), the method inside the subclass Dog is called. The displayInfo() method of the subclass overrides the same method of the superclass. Notice the use of the @Override annotation in our example.
Method overriding, in object-oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes.
Therefore, you cannot override two methods that exist in the same class, you can just overload them.
In object-oriented programming, users can inherit the properties and behaviour of a superclass in subclasses. A subclass can override methods of its superclass, substituting its own implementation of the method for the superclass's implementation.
Sometimes the overriding method will completely replace the corresponding functionality in the superclass, while in other cases the superclass's method must still be called from the overriding method. Therefore most programming languages require that an overriding method must explicitly call the overridden method on the superclass for it to be executed.
There are certain methods that do essential things, such as onCreate and onPause methods of activity. If you override them without calling the super method, those things won't happen, and the activity won't function as it should. In other cases (usually when you implement an interface) there is no implementation that you override, only declaration and therefore there is no need to call the super method.
One more thing, sometimes you override a method and your purpose is to change the behavior of the original method, not to extend it. In those cases you should not call thesuper method. An example for that is the paint method of swing components.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With