ZhengZhiren
ZhengZhiren

Reputation: 1312

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?

Upvotes: 3

Views: 2407

Answers (5)

ItSNeverLate
ItSNeverLate

Reputation: 739

Based on Android document: Unlike the activity lifecycle callback methods, you are not required to call the superclass implementation of these callback methods for service lifecycle callback methods.

Upvotes: 0

卢声远 Shengyuan Lu
卢声远 Shengyuan Lu

Reputation: 32004

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.

Upvotes: 0

Nanne
Nanne

Reputation: 64399

You must call them if the manual says so as @t-j-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 (e.g. '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.

Upvotes: 0

Stephen C
Stephen C

Reputation: 718778

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.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074208

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.

Upvotes: 7

Related Questions