public or private, does it really matter with Android variables

Octoth0rpe picture Octoth0rpe · Sep 19, 2012 · Viewed 13.7k times · Source

inside of a single activity, when defining components to be used only within that activity, what's the real difference between the following definitions:

Button  btnPower = null;
//or
private Button btnPower = null;
//or
public Button btnPower = null;

public void somethingUsingTheButton(){
  btnPower = (Button)findViewById(R.id.btnpower_id);
}

are there some "under the hood" conventions that should be thought about (garbage cleanup, memory, etc) that would suggest to always use private over public, if the entity itself is only ever going to be used inside the class it's written in?

Answer

pjco picture pjco · Sep 19, 2012

Private fields promote encapsulation

It's a generally accepted convention to use private unless you need to expose a field or method to other classes. Getting in this as a habit will save you a lot of pain in the long run.

However, there isn't anything inherently wrong with a public field or method. It causes no difference for garbage collection.

In some cases some types of access will affect performance, but they are probably a bit more advanced than the topic of this question.

One such case has to do with inner classes accessing outer class fields.

class MyOuterClass
{
    private String h = "hello";

    // because no access modifier is specified here 
    // the default level of "package" is used
    String w = "world"; 

    class MyInnerClass
    {
        MyInnerClass()
        {
            // this works and is legal but the compiler creates a hidden method, 
            // those $access200() methods you sometimes see in a stack trace
            System.out.println( h ); 

            // this needs no extra method to access the parent class "w" field
            // because "w" is accessible from any class in the package
            // this results in cleaner code and improved performance
            // but opens the "w" field up to accidental modification
            System.out.println( w ); 
        }
    }
}