Global variables in Java [duplicate]
Possible Duplicates:
Why are there no global variables in Java? Global variables in Java
Hi,
Is there any way to declare global Variables in java? or something with a wide scope like them? can anybody explain me why are global variables considered bad? any articles about this are really appreciated.
thank you
On any class, you can declare static variables:
class MyClass {
public static String MyString = "Some String";
...
}
And then reference them via:
MyClass.MyString;
You can create 'global' variables by declaring them within the scope of the class ie
public class Example {
String globalString = "this is global";
public static void main(String[] args){
String localString = "this is a local variable";
}
}
You can also create static variables which can be accessed by a method which has been declared static too.
A good discussion can be found here, Static Methods or Not? Global variables?
public static
will give enough scope to your variable for them to act as global variable. But think twice before doing so.
精彩评论