2024-09-21 08:00:04

Java中的全局变量

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


当前回答

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

 public static int global = 5;

}

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

GlobalImpl.global // 5

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

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

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

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

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

like

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

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

例如Calendar.JANUARY)

一般来说,Java没有任何全局变量。除局部变量外,所有变量都属于程序中定义的任何类的作用域。 我们可以用静态变量来表示全局变量的作用域。

实际上,在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是你声明它们的类名。