2024-09-21 08:00:04

Java中的全局变量

如何在Java中定义全局变量?


当前回答

很多很好的答案,但我想给出这个例子,因为它被认为是一个类访问另一个类的变量的更合适的方式:使用getter和setter。

The reason why you use getters and setters this way instead of just making the variable public is as follows. Lets say your var is going to be a global parameter that you NEVER want someone to change during the execution of your program (in the case when you are developing code with a team), something like maybe the URL for a website. In theory this could change and may be used many times in your program, so you want to use a global var to be able to update it all at once. But you do not want someone else to go in and change this var (possibly without realizing how important it is). In that case you simply do not include a setter method, and only include the getter method.

public class Global{
    private static int var = 5;

    public static int getVar(){
        return Global.var;
    }

    //If you do not want to change the var ever then do not include this
    public static void setVar(int var){
        Global.var = var;
    }
}

其他回答

理解问题

我将全局变量限定为可以在代码中的任何地方访问和更改的变量,而无需关心静态/实例调用或从一个类传递任何引用到另一个类。

通常是A类

public class A {
    private int myVar;

    public A(int myVar) {
        this.myVar = myVar;
    }

    public int getMyVar() {
        return myVar;
    }

    public void setMyVar(int mewVar) {
        this.myVar = newVar;
    }
}

并且想在类B中访问和更新myvar,

public class B{

    private A a;

    public void passA(A a){
        this.a = a;
    }

    public void changeMyVar(int newVar){
        a.setMyvar(newVar);
    }
}

你需要引用类a的一个实例,并像这样更新类B的值:

int initialValue = 2;
int newValue = 3;
A a = new A(initialValue);
B b = new B();
b.passA(a);
b.changeMyVar(newValue);
assertEquals(a.getMyVar(),newValue); // true

解决方案

所以我的解决方案,(即使我不确定这是否是一个好的实践),是使用单例:


public class Globals {
    private static Globals globalsInstance = new Globals();

    public static Globals getInstance() {
        return globalsInstance;
    }

    private int myVar = 2;

    private Globals() {
    }

    public int getMyVar() {
        return myVar;
    }

    public void setMyVar(int myVar) {
        this.myVar = myVar;
    }
}

现在你可以在任何地方获得全局唯一实例:

Globals globals = Globals.getInstance();
// and read and write to myVar with the getter and setter like 
int myVar = globals.getMyVar();
global.setMyVar(3);

要定义全局变量,可以使用静态关键字

public class Example {
    public static int a;
    public static int b;
}

现在你可以在任何地方访问a和b 通过调用

Example.a;

Example.b;

在Java中没有全局变量

然而,我们所拥有的是一个静态关键字,这就是我们所需要的。 在Java中,类之外不存在任何东西。static关键字表示一个类变量,与实例变量相反,它只有一个副本,并且它超越了创建的该类的所有实例,这意味着它的值可以在任何时候在所有实例之间更改和访问。

如果您需要一个可以超出作用域访问的全局变量,那么这就是您需要的变量,但它的作用域只存在于类所在的位置,仅此而已。

public class GlobalClass {
     public static int x = 37;
     public static String s = "aaa";
}

这样你就可以用GlobalClass访问它们。x和GlobalClass.s

一般来说,Java没有任何全局变量。除局部变量外,所有变量都属于程序中定义的任何类的作用域。 我们可以用静态变量来表示全局变量的作用域。