5

Why are the lifeCycle methods in android have access specifiers as protected ?


what i understand about Access-specifiers is as below::

enter image description here


  • But why should we need to make all the life-cycle methods as protected
  • I notice this when i override the lifecycle methods
  • I know over-riding the methods of Activity class as methods in Activity class are defined protected
  • But why are they defined as protected

Devrath
  • 42,072
  • 54
  • 195
  • 297

3 Answers3

6
  • They are protected for encapsulation within the framework package android.app and subclasses.
  • They are to be called by android.app.ActivityManager (same package) only. Depending on the method implementation, things could get messed up, if one can call those methods arbitrarily, from anywhere.

So, this is by design and that design helps to avoid certain conceptual errors. If you really must have a public method, just implement one and use it from outside and within the corresponding lifecycle method.
However, though not recommended in this case, one could override protected methods with public methods.

Community
  • 1
  • 1
Sam
  • 7,778
  • 1
  • 23
  • 49
1

i am defining here why public and protected and how it work:

It's useful to have public onClick methods because you can "force" certain buttons to be clicked programmatically. A common example of this is causing the same to code to execute when the user presses the enter key, or pressed the Submit button.

I don't think Android calls Activity.onCreate directly. Note that Activity inherits from Context (which does have a public constructor). It is my understanding that the constructor triggers some events to occur, and the onCreate/Pause/Resume/Destroy methods are called internally to the class at the appropriate time.

For example, when you create an activity, the view XML file has to be parsed and inflated. This happens automatically, so there's something happening behind the scenes that you don't directly control.

Hamad
  • 5,096
  • 13
  • 37
  • 65
1

Not public because those lifecycle methods are essentially used internally by the SDK and are not meant to be called by any other classes (you are not supposed to call anywhere activity.onResume() from any class, this is done automatically).

Not private to allow some custom code to be ran by subclasses.

Vincent Mimoun-Prat
  • 28,208
  • 16
  • 81
  • 124