Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I know when/where to invoke the overridden method of the super class

Tags:

java

android

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

like image 709
Henry Avatar asked Jan 23 '23 06:01

Henry


2 Answers

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:

  • call super first
  • call super last
  • handle some cases yourself (customizations), call super for the rest
  • never call super

Hopefully the documentation for the particular class you're overriding will tell you if/when it's necessary to call super.

like image 153
David Gelhar Avatar answered Feb 04 '23 03:02

David Gelhar


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.

like image 33
JRL Avatar answered Feb 04 '23 02:02

JRL