Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are there no global variables in Java? [closed]

Why are there no global variables in Java?

like image 216
developer Avatar asked Apr 07 '11 12:04

developer


2 Answers

The answer is to your question is, because Java doesn't support global variables, by design. Java was designed with object-oriented principles in mind and as such, every variable in Java is either local or a member of a class.

Static class members are globally-accessible, which is certainly one possible definition of a global variable, depending upon your interpretation of the term. To be pedantic, whilst Static class members are accessible via the class name and therefore across multiple scopes, they are still class members; and therefore not truly global variables as such.

Java's lack of support for global variables is a good thing, as using global variables is a design anti-pattern.

like image 122
razlebe Avatar answered Nov 19 '22 05:11

razlebe


Global variables are usually a design flaw.

Your components should be self-contained and should not need any global state.
Instead, use private static fields.

like image 25
SLaks Avatar answered Nov 19 '22 03:11

SLaks