2024-09-21 08:00:04

Java中的全局变量

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


当前回答

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

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

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

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

其他回答

为了允许对另一个类的静态成员进行非限定访问,你也可以执行静态导入:

import static my.package.GlobalConstants;

现在,不是打印(GlobalConstants.MY_PASSWORD); 你可以直接使用常量:print(MY_PASSWORD)

“import”后面的“static”修饰符是什么意思?决定。

考虑Evan Lévesque关于承载常量的接口的回答。

public class GlobalImpl {   

 public static int global = 5;

}

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

GlobalImpl.global // 5
// 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 Example {
    public static int a;
    public static int b;
}

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

Example.a;

Example.b;

如果没有静电,这也是可能的:

class Main {
  String globalVar = "Global Value";

  class Class1 {
    Class1() {
      System.out.println("Class1: "+globalVar);
      globalVar += " - changed";
  } }
  class Class2 {
    Class2() {
      System.out.println("Class2: "+globalVar);
  } }

  public static void main(String[] args) {  
    Main m = new Main();
    m.mainCode();
  }
  void mainCode() {
    Class1 o1 = new Class1();
    Class2 o2 = new Class2();
  }
}

/*
Output:
Class1: Global Value
Class2: Global Value - changed
*/