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;
    }
}

其他回答

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

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

你不。这是故意的。即使你能做,你也不应该做。

也就是说,您可以在一个名为Globals的类中创建一组公共静态成员。

public class Globals {
   public static int globalInt = 0;
   ///
}

但你真的不应该:)。认真. .不要这样做。

创建一个独立的文件。java使用第一个解决方案,就可以了。你也可以在应用程序中这样做,例如,全局变量对你当前的应用程序是特殊的,等等:

在开头创建一个类,并在其中声明你的变量:

class Globals {
  static int month_number;
  static String month_name;
}

然后你可以访问这些变量——使用它们作为“全局变量”。Month_number ',等等——从你的应用程序的任何地方。

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

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

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

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

在Java中没有全局变量,但是有带有公共字段的全局类。您可以使用java 5的静态导入特性使其看起来几乎像全局变量。