2024-09-21 08:00:04

Java中的全局变量

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


当前回答

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

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

其他回答

// 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中没有全局变量

然而,我们所拥有的是一个静态关键字,这就是我们所需要的。 在Java中,类之外不存在任何东西。static关键字表示一个类变量,与实例变量相反,它只有一个副本,并且它超越了创建的该类的所有实例,这意味着它的值可以在任何时候在所有实例之间更改和访问。

如果您需要一个可以超出作用域访问的全局变量,那么这就是您需要的变量,但它的作用域只存在于类所在的位置,仅此而已。

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

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

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

Example.a;

Example.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是你声明它们的类名。

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