2024-09-21 08:00:04

Java中的全局变量

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


当前回答

正如你可能从答案中猜到的那样,Java中没有全局变量,你唯一能做的就是创建一个具有静态成员的类:

public class Global {
    public static int a;
}

你可以在Global中使用它。在其他地方。然而,如果你使用Java 1.5或更高版本,你可以使用导入静态魔法,使它看起来更像一个真正的全局变量:

import static test.Global.*;

public class UseGlobal {
    public void foo() {
        int i = a;
    }
}

瞧!

现在这还远远不是最佳实践,所以你可以在广告中看到:不要在家里这样做

其他回答

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

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

public class GlobalImpl {   

 public static int global = 5;

}

你可以在任何地方打电话:

GlobalImpl.global // 5

你最好使用依赖注入:

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

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

另一种方法是创建一个这样的界面:

public interface GlobalConstants
{
  String name = "Chilly Billy";
  String address = "10 Chicken head Lane";
}

任何需要使用它们的类只需要实现接口:

public class GlobalImpl implements GlobalConstants
{
  public GlobalImpl()
  {
     System.out.println(name);
  }
}

一般来说,全局变量(我假设您正在与C进行比较,Cpp)定义为公共静态final

like

class GlobalConstant{
    public static final String CODE  = "cd";
}

enum在这样的场景中也很有用:

例如Calendar.JANUARY)