When we override a method in a subclass, we call the su开发者_如何学Cperclass 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 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.
For some method you must call the super method to init some object or variable (else you get a supernotcall exception), for others you can call it but you do note have.
There are a lot of things that Android's API would be doing in the onCreate (or any other on_____) method of you Activity class.
Now when you override the method, your implementation would be used instead of the one in the activity class while running the activity, since that's what overriding is meant for. It overrides the parent's (i.e. the Activity class) implementation and replaces it with the child's implementation (i.e. Your class).
So Android enforces this rule that you always need to call the parent's implementation in addition to your own implementation so that the parent's implementation (which contains many important things) remains intact in addition to your implementation.
I hope this is elaborate enough and makes is clear.
精彩评论