2024-09-21 08:00:04

Java中的全局变量

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


当前回答

非常简单:

class UseOfGlobal
{
private static int a;
private static int b;
}

但是在方法块中尽可能地定义局部变量总是好的。

其他回答

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

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

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

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

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

public final class Tools {
  public static int a;
  public static int b;
}

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

Tools.a;
Tools.b;

你说得对……特别是在J2ME中… 可以通过将NullPointerException放入MidLet构造函数中来避免 (程序初始化)这行代码:

new Tools();

这确保了Tools将在任何指令之前分配 它使用了它。

就是这样!

// 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

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

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

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

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

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

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