Java Global Variables: Definition Methods

There are two ways to define global variables in Java.

  1. Variables are defined inside a class, but outside of any method. These variables are known as “instance variables” or “member variables” because they belong to the instance or object of the class. These variables are visible throughout the class and can be accessed and modified by any method within the class.
public class MyClass {
    // 实例变量
    private int myVariable;
    
    // 方法
    public void myMethod() {
        // 在方法中访问和修改实例变量
        myVariable = 10;
    }
}
  1. unchanged
public class MyClass {
    // 静态变量
    private static int myVariable;
    
    // 方法
    public static void myMethod() {
        // 在方法中访问和修改静态变量
        myVariable = 10;
    }
}

It should be noted that the scope of a global variable is the entire class, and it can be accessed and modified by any method within the class.

bannerAds