简体   繁体   中英

Do I need to call “super.XXX” whenever I override a method?

Say, if I don't call super.onPause in a override method from superclass Activity , I would get an error when onPause() is called. But errors don't show up when I have no super.XXX calls in methods ( onCreate , onStartCommand , ...) of a class derived from Service .

So on what conditions should I call super.XXX in a override method?

The documentation tells you that you need to call onPause if you derive the Activity class:

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

The Service docs don't require that in the onStartCommand documentation .

In general (not specifically in Android stuff), when you derive, you should call through to the superclass's methods unless you know you shouldn't. It's a decision that needs to be case-by-case, but the default (I'd say) would be that you do it.

So on what conditions should I call super.XXX in a override method?

It is not possible to give a useful answer to this. It entirely depends on the intended purpose and behavior of the override method and the method being overridden.

If you don't know, you need to do one or more of the following:

  • read the javadocs for the method,
  • look at examples of classes that implement the method, and / or
  • look at the code of the method you are overriding.

In this particular case, the javadoc gives a clear answer.

You must call them if the manual says so as @tj-crowder said.

it says

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

If not, then the reasoning is that if you are calling a function, do you want the 'normal' behaviour to be started?

For instance, if you override the onKeyDown() You could do something after a certain key is pressed (eg 'back'). Then you have the choice:

  • If you want the normal action of 'back' to be executed, call the super
  • If you DON'T want to run the normal action, don't call it.

Client code can only know subclass Activity (call it MyActivity ), Client code cannot know Activity . However, MyActivity can know its base class Activity.

If the overridden method onPause() is same as its base class, you don't need to override it explicitly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM