Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why no global variables in java like C++?

Tags:

java

Why there are no global variables in java? If I like to use any variable in all classes of a program then how can I do that?

like image 378
giri Avatar asked Jan 28 '10 20:01

giri


2 Answers

If you really want to do that, make it a public static variable.

However, you'd be advised to try not to - it makes for less elegant, harder to maintain, harder to test code.

like image 57
Jon Skeet Avatar answered Oct 12 '22 00:10

Jon Skeet


Global variables (in the Java context - public static variables) are bad, because:

  • harder to maintain - you can't put a breakpoint or log each change to a variable, hence unexpected values at runtime will be very hard to track and fix

  • harder to test - read Miško Havery's post

  • harder to read - when someone sees the code he'll wonder:

    • where does this come from?
    • where else it is read?
    • where else it is modified?
    • how can I know what's its current value?
    • where is it documented?

To make one clarification that seems needed - variables != constants. Variables change, and that's the problem. So having a public static final int DAYS_IN_WEEK = 7 is perfectly fine - no one can change it.

like image 22
Bozho Avatar answered Oct 12 '22 02:10

Bozho