Home > Net >  Whats the difference between initialising a variable before and after onCreate()?
Whats the difference between initialising a variable before and after onCreate()?

Time:06-23

For example, if I want to make a list called List<String> stringList;, whats the difference if I call it stringList = new ArrayList<>(); in onCreate() and just doing List<String> stringList = new ArrayList<>(); ?

And if I use List<String> stringList; before onCreate(), why declare it private?

CodePudding user response:

The objects which are not dependent on Activity creation process can b created and initialized and define before onCreate() method. But the things or objects which are dependent with that Activity are declared before onCreate() but must be initialized in onCreate(). For example if your registering a view (like button) in Activity, then you have to initialize it in MainActivity. Hope so first thing is cleared.

2nd one, it is not necessary to make a variable/function private or public. But best practice is that if you are using variable/function which relate only with that activity then you should make it private.

  • Related