2024-09-21 08:00:04

Java中的全局变量

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


当前回答

从概念上讲,全局变量又称实例变量,是类级变量,即类级变量。,它们定义在类内部,但在方法之外。为了使它们完全可用,并直接使用它们,提供静态关键字。 因此,如果我正在编写一个简单的算术运算程序,它需要一个数字对,然后两个实例变量定义如下:

public class Add {
    static int a;
    static int b; 
    static int c;

    public static void main(String arg[]) {
        c=sum();
        System.out.println("Sum is: "+c); 
    }

    static int sum() {
       a=20;
       b=30;
       return a+b;   
    }
}

Output: Sum is: 50

此外,在实例变量之前使用static关键字使我们不必反复为相同的变量指定数据类型。直接写出变量即可。

其他回答

你最好使用依赖注入:

public class Globals {
    public int a;
    public int b;
}

public class UsesGlobals {
    private final Globals globals;
    public UsesGlobals(Globals globals) {
        this.globals = globals;
    }
}

很多很好的答案,但我想给出这个例子,因为它被认为是一个类访问另一个类的变量的更合适的方式:使用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;
    }
}
// Get the access of global while retaining priveleges.
// You can access variables in one class from another, with provisions.
// The primitive must be protected or no modifier (seen in example).

// the first class
public class farm{

  int eggs; // an integer to be set by constructor
  fox afox; // declaration of a fox object

  // the constructor inits
  farm(){
    eggs = 4;
    afox = new fox(); // an instance of a fox object

    // show count of eggs before the fox arrives
    System.out.println("Count of eggs before: " + eggs);

    // call class fox, afox method, pass myFarm as a reference
    afox.stealEgg(this);

    // show the farm class, myFarm, primitive value
    System.out.println("Count of eggs after : " + eggs);

  } // end constructor

  public static void main(String[] args){

    // instance of a farm class object
    farm myFarm = new farm();

  }; // end main

} // end class

// the second class
public class fox{

  // theFarm is the myFarm object instance
  // any public, protected, or "no modifier" variable is accessible
  void stealEgg(farm theFarm){ --theFarm.eggs; }

} // end class

除了常量,没有什么是全局的。

public class MyMainClass {
    public final static boolean DEBUGMODE=true;
}

把它放在你的主类中。在其他。java文件中,通过以下方式使用它:

if(MyMainClass.DEBUGMODE) System.out.println("Some debugging info");

确保当你把你的代码从剪辑室移出并发布时,你删除或注释掉了这个功能。

如果你有一个常用的方法,比如随机发生器,我建议你创建一个“工具箱”包!所有编码员都应该有一个,然后当你想在.java中使用它时,只需导入它!

理解问题

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

通常是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);