How can global variables be defined in Java?
In Java, you can use the keyword static to define global variables. These variables, defined as static, belong to the class rather than any specific object instance. Global variables can be accessed throughout the entire class, regardless of the method.
Here is an example:
public class MyClass {
// 全局变量
static int globalVariable = 10;
public static void main(String[] args) {
// 访问全局变量
System.out.println(globalVariable); // 输出: 10
}
}
In the example above, globalVariable is defined as a global variable and can be directly accessed and used in the main method.