开发者

Global variables in Java [duplicate]

This question already has answers here: 开发者_开发百科 Closed 11 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜