public or private, does it really matter with Android variables public or private, does it really matter with Android variables android android

public or private, does it really matter with Android variables


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 );         }    }}


well,one important point is that defining variables as private is the standard in java programming.So calling directly variables on objects will at least appear strange for other people that may possibly read your code.

One other thing I'd say is that if you are not alone coding on a project is always a good practice to limit the visibility of the attributes that are key on the class implementation to avoid strange work around that other developers may come up with.

I personally don't know if those modifiers are used to compiling and optimization purpose.

to conclude as I think every experienced java coder I strongly sujest to use this pattern in the definition of attributes.


The scope of visibility has nothing to do with the garbage collector or memory management

You will want to reduce the scope of visibility as much as possible so your code can be easier to maintain.