Reputation: 554
Android requires that all Activity sub-classes invoke super methods from their lifecycle methods. An exception is thrown if the super method is not invoked. Why does Android use a RuntimeException mechanism to force super methods to be called. Why does it not use the 'Template' design pattern so that super methods get executed automatically before the child methods. For example onDestroy() can be handled as follows :-
Class Activity{
public void onDestroyFrmwork()
{
//do whatever the super onDestroy() method has to do
onDestroy();//this will invoke the subclass method.
}
public void onDestroy()
{
//empty. will get overridden by subclasses.
}
}
Upvotes: 1
Views: 164
Reputation: 83303
Your application won't work correctly if you don't call the superclass methods, so the API throws a RuntimeException
to make sure you don't forget to do so.
Upvotes: 0
Reputation: 10672
I know I am answering this question 11 months after it was asked. I guess the reason is that the order of calling the super method cannot be determined in advance. For example, I might want to do my clean up before calling super.onDestroy()
, after super.onDestroy()
or even mix it up like follows:
@Override
protected void onDestroy() {
// Do some initial clean-up
preDestroy();
//Then call super
super.onDestroy();
//In the end do some final clean-up
postDestroy();
}
This example is for the sake of argument; but I'm sure you would come across real world examples if you look hard enough.
This kind of mixed ordering would be hard to achieve using Template design pattern.
Upvotes: 2