The difference between static variables and instance variables in JAVA basics

In the daily development of JAVA, we inevitably need to declare some static variables and instance variables while encapsulating the class. This article mainly explains some of the differences between them.

First of all, on the syntax definition: when declaring static variables, you need to add the static keyword in front of them to modify. Instance variables are not required.

Then the difference in the compilation process: static variables belong to the static storage method. As long as the program loads and compiles the bytecode of the current class, the static static variables can be called directly without creating any instance objects (static variables are stored directly after the class is compiled. memory space will be allocated). An instance variable belongs to a certain attribute of a class object. When using it, the object needs to be instantiated before it can be called (instance variables need an instance of the class object before allocating memory space).

Take a very simple example:

    public class VariantDemo {
        public static int staticVar = 0;
        public int instanceVar = 0;

        public VariantDemo() {
            instanceVar = 1;
        }
    }
In this test class, a static variable staticVar and an instance variable instanceVar are declared respectively. when in use
    public class TestClass {
        public static void main(String[] args) {
            //The use of instance variable instanceVar needs to instantiate the VariantDemo class first
            VariantDemo variantDemo = new VariantDemo();
            int instanceVar = variantDemo.instanceVar;
            //Static variables can be used directly by the class name. The variable name
            int staticVar = VariantDemo.staticVar;

            System.out.print("staticVar=" + staticVar + "\ninstanceVar=" + instanceVar);
        }
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324691117&siteId=291194637