Public onCreate () or protected onCreate ()?

When reading the book "Hello, Android", I noticed that:

Each java file using the method onCreate(Bundle savedInstanceState)has a secure EXCEPT access key in the main activity of the program [, which has: public void onCreate(Bundle savedInstanceState)].

Why is the method onCreate publicin the main activity of the program, but protectedeverywhere?

+5
source share
4 answers

onCeate () is protected to avoid calling it from an activity object.

MyActivity activity = new MyActivity();
activity.onCreate(args);  // which doesn't make sense because activity is not yet created

Since this method is only called when an activity is created, calling it yourself will most likely give you a nullpointerException , since this activity has not yet been created. S / O Message

+2

. , , : ( ), ( )

+1

It can also be protected. There is nothing important or wise in this.

0
source

There is no reason to make this method publicly available (but it does not affect anything). You should not call it manually anyway.

By the way, Intellij IDEA has a public activity template onCreate. This may be the reason this method is published in the book.

0
source

All Articles