Q:

Use of Global variables

Why is it that when I read others code I frequently see extensive use of "Global variables"?
For instance in Java code:
public class SomeClass {
   Button btn1;
   private void someMethod() {
       btn = new Button();
   }
}

btn1 is declared as "global" and a "convenient" variable to be used as easy access throughout the class. But when there is no modifier on it, it defaults to default access in Java.
Could this be a security risk? Why don't people declare them with private modifier right away if they are only planning to use them in only one specific class?

A:

It is no global variable (does such a thing even exist in Java? I guess it depends on one's definition of global). It is still a class member. 
The default visibility is package-private, so the variable is not public but can be accessed by other classes in the same package.
Normally one should strive for the "best" data encapsulation but there might be uses cases where this is appropriate.

A:

btn1 is not a global variable. it is an instance variable of the class
if no access modifier is specified, then it defaults to "package" level access i.e. btn1 is accessible to all the classes which belong to the same package as SomeClass
if SomeClass is just a data holder and immutable (no setters etc) then this is perfectly OK.
It is always better to be as much more restrictive as possible when it comes to the instance variables.

A:

That's not a global variable. It has the default access, so it's not globally visible, and it's an instance member, which means it's scoped to an instance of SomeClass. The nearest equivalent to a global variable in Java is a public static field in a public class. Even in that case it's only global with respect to the classloader for the container class you're using - a different classloader running in the same JVM and loading the same container class would have a separate static variable.
Having said all of this, I personally disapprove of fields being anything other than private, to aid encapsulation. (That doesn't give you encapsulation on its own, of course, but it's a start.) Fields are part of the implementation of the class, which should be modifiable without affecting anyone only relying on the API of the class.

