This question occured to me while programming a Android application, but it seems to be a general programming question more.
The situation is, I am extending (subclass-ing) an class from a library, and overriding a method. how do I know if I should invoke the method of super-class? and when? (in the beginning of the overridden method or in the end?)
For example, I am overriding the method "public boolean onCreateOptionsMenu(Menu menu)" from class "Activity" in Android platform. And I saw someone write "return super.onCreateOptionsMenu(menu)" in the end of the method, in an example. But how do I know it should be done this way? and it is correct or not? what's the difference if I begin my method with "super.onCreateOptionsMenu(menu)"?
BR, Henry
I don't think you can answer this question in the abstract: it depends on the behavior of the superclass method you're overriding.
Depending on circumstances, it may be appropriate to:
Hopefully the documentation for the particular class you're overriding will tell you if/when it's necessary to call super.
Unfortunately, there is no rule for this. You need to refer to the API docs and call super if the docs say you need to.
One hint as to whether you'll probably need to or not in Android's case is if the method you're overriding is one of the lifecycle methods. In this case, you can be fairly certain that you need to call super.
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