What is the difference between static variables and instance variables?

In Java, static variables and instance variables are two different variable types, and they have the following differences:

  1. A static variable belongs to the class, not any instance of the class. Instance variables belong to instances of classes.

  2. There is only one copy of a static variable and it is always the same no matter how many times the class is instantiated. Instance variables Each instance has its own copy.

  3. Static variables can be accessed directly from the class without instantiation. Instance variables must be accessed after instantiating the object.

  Next, let's look at a simple Java code example to demonstrate the difference between static variables and instance variables:

public class Example {
    static int staticVariable = 10; // 静态变量
    int instanceVariable = 20; // 实例变量

    public static void main(String[] args) {
        Example obj1 = new Example();
        Example obj2 = new Example();

        // 静态变量可以通过类名直接访问
        System.out.println("静态变量staticVariable值为:" + Example.staticVariable);

        // 实例变量必须通过实例对象访问
        System.out.println("obj1的实例变量instanceVariable值为:" + obj1.instanceVariable);
        System.out.println("obj2的实例变量instanceVariable值为:" + obj2.instanceVariable);

        // 修改静态变量的值
        Example.staticVariable = 30;

        // 打印修改后的静态变量值
        System.out.println("静态变量staticVariable值为:" + Example.staticVariable);
        System.out.println("obj1的静态变量staticVariable值为:" + obj1.staticVariable);
        System.out.println("obj2的静态变量staticVariable值为:" + obj2.staticVariable);

        // 修改实例变量的值
        obj1.instanceVariable = 40;

        // 打印修改后的实例变量值
        System.out.println("obj1的实例变量instanceVariable值为:" + obj1.instanceVariable);
        System.out.println("obj2的实例变量instanceVariable值为:" + obj2.instanceVariable);
    }
}

  The output is as follows:

静态变量staticVariable值为:10
obj1的实例变量instanceVariable值为:20
obj2的实例变量instanceVariable值为:20
静态变量staticVariable值为:30
obj1的静态变量staticVariable值为:30
obj2的静态变量staticVariable值为:30
obj1的实例变量instanceVariable值为:40
obj2的实例变量instanceVariable值为:20

  As you can see, there is only one copy of the static variable, which can be directly accessed through the class name. Instance variables Each instance has its own copy and must be accessed through the instance object. When modifying a static variable, all instances are affected. When modifying an instance variable, only that instance is affected.

Guess you like

Origin blog.csdn.net/Blue92120/article/details/130683705