Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the impact of code if we write before or after super() function in override function

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?

like image 305
M.ArslanKhan Avatar asked Aug 30 '15 14:08

M.ArslanKhan


1 Answers

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().

like image 195
adelphus Avatar answered Sep 28 '22 09:09

adelphus