Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are lifecycle methods in activity class defined with protected access specifier

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

like image 593
Devrath Avatar asked Nov 23 '13 11:11

Devrath


People also ask

What is the point of private access specifier?

Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members.

Which lifecycle method is mandatory to override in subclass of application?

stop() − An empty method which can be overridden, here you can write the logic to stop the application. init() − An empty method which can be overridden, but you cannot create a stage or scene in this method.

Why are access specifiers needed?

Access specifiers define how the members (attributes and methods) of a class can be accessed. In the example above, the members are public - which means that they can be accessed and modified from outside the code. However, what if we want members to be private and hidden from the outside world?

Which activity life cycle methods is called once the activity is no longer visible?

onStop(): Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one.


1 Answers

  • 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.

like image 184
Sam Avatar answered Nov 10 '22 04:11

Sam