Static, private and final variables

0

I have a question that has been disturbing me for a long time:

  • What is the advantage of creating a static and final variable (both private and public)?

  • If I have a primitive or simple class variable (String for example), they have final values and are private. Should they be static?

  • In the previous case, what is the impact of memory on an Android device?

As far as I know, creating type variables that interact with the application context can cause a memory leak, so I know this is a "bad practice". But what about simpler variables?

* Note: I installed a plugin in Android Studio that told me to put end up in local variables and that are argument. I did not understand the real need, so I did not hesitate to ask here, for anyone who knows.

    
asked by anonymous 22.07.2017 / 14:01

1 answer

1

Final variables are just constant, ie they can not receive new values.

Static variables are class variables, that is, they do not depend on the creation of an object to be used and all objects of this class will have access to the value of this variable.

Private and public variables are only access restrictions that you configure. Private only the object itself accesses and public anyone.

The combination of the above definitions will depend on the strategy and logic you are implementing. I've never heard of any difference in performance between them. At least in training, even the officials I've done have never raised that question.

Class variable in place of primitive (Integer instead of int, eg) have come to add features that the primitives do not have (eg check if it is null). It has less performance, but it's so insignificant that it's not worth it to stop using it thinking about it.

The part of the context you mentioned did not understand.

Android Studio tips are intended to increase code efficiency. For example: if you create a variable that does not change its value and no other method accesses, why not create it as constant and local within the method that uses it?

    
22.07.2017 / 14:25