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?
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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With