2024-09-21 08:00:04

Java中的全局变量

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


当前回答

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

public class Example {
    public static int a;
    public static int b;
}

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

Example.a;

Example.b;

其他回答

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

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

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

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

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

Tools.a;
Tools.b;

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

new Tools();

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

就是这样!

非常简单:

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

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

实际上,在java OO程序中没有“GLOBAL”的概念

尽管如此,你的问题背后还是有一定道理的,因为在某些情况下,你想在程序的任何部分运行一个方法。 例如——random()方法在Phrase-O-Matic应用程序;它是一个方法应该可以从程序的任何地方调用。

为了满足上面提到的"我们需要类全局变量和方法"

将一个变量声明为全局变量。

 1.Mark the variable as public static final While declaring.

将一个方法声明为全局方法。

 1. Mark the method as public static While declaring.

因为我将全局变量和方法声明为静态的,你可以在任何地方调用它们,只需借助下面的代码

ClassName。X

注意:根据需求,X可以是方法名或变量名,ClassName是你声明它们的类名。

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