Java Global Variables Guide
In Java, global variables are typically defined as class member variables. Global variables can be accessed anywhere within the class, not limited to specific methods or code blocks.
The way to define global variables is as follows:
public class MyClass {
// 全局变量
public int globalVar1;
public String globalVar2;
public static void main(String[] args) {
// 在类的任何方法中可以访问全局变量
MyClass myObj = new MyClass();
myObj.globalVar1 = 10;
myObj.globalVar2 = "Hello";
System.out.println(myObj.globalVar1);
System.out.println(myObj.globalVar2);
}
}
In the example above, globalVar1 and globalVar2 are defined as global variables of the MyClass class, which can be accessed and modified in the main method.