Reputation: 1010
One of the requirements of basic Android development (according to the Google docs) is that when you override the activity's lifecycle methods (onCreate, onResume, onPause, etc.), you must call the parent's method first:
@Override
protected void onResume()
{
super.onResume();
}
Why doesn't the Android API use a non-virtual interface pattern to enforce this behavior, rather than relying on developers to remember to do so?:
Android's Activity Base class could look something like this (crude example):
public class Activity
{
public final void onResume()
{
// do important things here
virtualOnResume();
}
protected abstract void virtualOnResume();
}
Child class written by Android developer:
public class MainActivity extends Activity
{
@Override
protected void virtualOnResume()
{
// do custom stuff here, without needing to call super.onResume()
}
}
I haven't encountered a case where I need to write any instructions prior to calling the super method. Is there any time we should NOT call the super method, or not call it first? If it truly must always be first for any particular method in the life cycle, what was the reason behind the design decision not to use a NVI pattern to enforce it?
UPDATE: Been developing for Android for a while now, everyone at work uses my BaseActivity NVI class, and I've still yet to encounter a reason NOT to use an NVI for all lifecycle methods but the onCreate one. It appears that those who answered/commented in defense of the existing API design don't really have a justification, or don't really seem to understand what an NVI pattern is, so I'm going with the assumption that there is no good reason, that it's "just how it is."
Upvotes: 0
Views: 1274
Reputation: 5330
This is an API design choice. It keeps the API surface smaller (less methods) and is a standard pattern (http://en.wikipedia.org/wiki/Decorator_pattern).
Upvotes: 0
Reputation: 18320
You do not have to call super method as first statement of your method. Sometimes you might want to do stuff before and after super method is invoked.
See FragmentActivity for example:
@Override
protected void onCreate(Bundle savedInstanceState) {
mFragments.attachActivity(this, mContainer, null);
// Old versions of the platform didn't do this!
if (getLayoutInflater().getFactory() == null) {
getLayoutInflater().setFactory(this);
}
super.onCreate(savedInstanceState);
NonConfigurationInstances nc = (NonConfigurationInstances)
getLastNonConfigurationInstance();
if (nc != null) {
mAllLoaderManagers = nc.loaders;
}
if (savedInstanceState != null) {
Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
mFragments.restoreAllState(p, nc != null ? nc.fragments : null);
}
mFragments.dispatchCreate();
}
Upvotes: 4