How can static variables be defined in Java?

In Java, static variables can be defined by adding the keyword “static” before the variable declaration. Static variables belong to the class rather than the instance object, and are initialized when the class is loaded, with only one copy shared by all instance objects.

Here is the syntax for defining static variables:

访问修饰符 static 数据类型 变量名;

The access modifier specifies the access level of the static variable (e.g. private, public, protected, etc.).

Here is a simple example:

public class MyClass {
    static int count;  // 定义一个静态变量count
    
    public static void main(String[] args) {
        count = 10;  // 可以直接通过类名访问静态变量
        System.out.println("count = " + count);
    }
}

In this example, a static variable count is defined and accessed and assigned to it using the class name MyClass.

bannerAds