问题
According to this post Global variables in Java it describes how to define a global variables in java by using static
public class Example {
public static int a;
public static int b;
}
But at same time in other post Why are there no global variables in Java? this question contradicts . So my question is what exactly is global variable ? Do java supports global variables ?if yes ,how? if no ,why? and how java global variables(if there are any) are different from c++ global variables?
回答1:
I think that we can argue that there is no global
keyword in java but your example can be treated like a global.
In most languages where you can define a global variable the problem is that they pollute the global namespace and name clashes can occur (like in php). In this regard there are no globals in java since there is no global namespace: variables are always in a class.
So the main thing is: there is no explicit globan in java and there is no globan namespace in java. This frees you from name clashes and accidental overwrites which is a good thing.
But there is nothing stopping you from creating a Global
class with a lot of public static
fields in it.
Please note that most guys (including me) would break both of your hands for doing so. :)
回答2:
a gloabal variable is used by many functions without need to enter it in the input of these functions. Expert advice to don't use them.
回答3:
A global variable is a variable which can be accessed from anywhere (from any part of the program). Thus a public static variable in any Java class is global.
来源:https://stackoverflow.com/questions/24060921/is-there-anything-called-global-variable-in-java