I am confused about super()
function call in overriden functions.
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
What is the impact of code written before or after super.onDestroy()
or
super.onPause()
or other super functions in all types of overriden methods in android?
In general, it's good practise to allow base classes to initialize first and destroy last - that way, any initial state from base classes that a derived class depends upon will have been sorted out first and, conversely, any derived class cleanup code can rely on the base class data still being valid.
In Android, I extend this behaviour to the onPause
and onResume
:
@Override
protected void onCreate(Bundle savedInstanceState) {
// let Android initialise its stuff first
super.onCreate();
// now create my stuff now that I know any data I might
// need from the base class must have been set up
createMyStuff();
}
@Override
protected void onDestroy() {
// destroy my stuff first, in case any destroying functionality
// relies upon base class data
destroyMyStuff();
// once we let the base class destroy, we can no longer rely
// on any of its data or state
super.onDestroy();
}
@Override
protected void onPause() {
// do my on pause stuff first...
pauseMyStuff()
// and then tell the rest of the Activity to pause...
super.onPause();
}
@Override
protected void onResume() {
// let the Activity resume...
super.onResume();
// and then finish off resuming my stuff last...
resumeMyStuff();
}
In reality, the onPause()
and onResume()
aren't really affected by the order because they do so little to affect the state of the activity. But it is extremely important to make sure that creation and destruction follow the base-create-first, base-destroy-last order.
But, exceptions to rules always exist and a common one is that if you want to change the theme of an Activity programatically in your onCreate()
method, you must do it before calling super.onCreate()
.
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