Detailed explanation of the function and usage of static in Java

1.1 overview:

Static is a static modifier. What is a static modifier? As we all know, any variable or code in the program is stored by the system automatically allocating memory during compilation, and the so-called static means that the memory allocated after compilation will always exist, and this space will not be released until the program exits, that is, as long as the program is running, this memory will always exist. What's the point? In Java programs, everything is an object, and the abstraction of an object is a class. If a class wants to use its members, it must instantiate the object first and then access these members through the reference of the object. However, members decorated with static can add "." through the class name Direct access.

Static means "global" or "static". It is used to modify member variables and member methods. It can also form static static code blocks. However, there is no concept of global variables in the Java language.

Member variables and member methods modified by static are independent of any object of the class. That is, it does not depend on class specific instances and is shared by all instances of the class. As long as the class is loaded, the Java virtual machine can find them in the method area of the runtime data area according to the class name. Therefore, a static object can be accessed before any of its objects are created without referencing any objects.

Static member variables and member methods decorated with public are essentially global variables and global methods. When declaring the object city of its class, a copy of the static variable is not generated, but all instances of the class share the same static variable.

The static variable can be decorated with private, which means that this variable can be used in the static code block of the class or in other static member methods of the class (of course, it can also be used in non static member methods - nonsense), but it can not be directly referenced by the class name in other classes, which is very important. In fact, you need to understand that private is limited access, and static means you can use it without instantiation, which is much easier to understand. Static is preceded by other access key words, and so on.

Member variables and member methods modified by static are customarily called static variables and static methods, which can be accessed directly through the class name. The access syntax is:

Class name Static method name (parameter list...)

Class name Static variable name

The code block decorated with static represents the static code block. When the Java virtual machine (JVM) loads the class, it will execute the code block (very useful, ha ha).

1.2 static variable

Class member variables can be classified according to whether they are static or not: one is the variable modified by static, which is called static variable or class variable; The other is variables that are not modified by static, called instance variables. The difference between the two is:

There is only one copy of static variables in memory (saving memory). The JVM allocates memory only once for static variables. During class loading, the memory allocation of static variables can be directly accessed by class name (convenient). Of course, it can also be accessed through objects (but this is not recommended).

For instance variables, memory will be allocated once for instance variables without creating an instance. Instance variables can have multiple copies in memory without affecting each other (flexible).

1.3 static method

Static methods can be called directly through the class name, and any instance can also be called. Therefore, this and super keywords cannot be used in static methods. You cannot directly access the instance variables and instance methods of the class (that is, member variables and member methods without static). You can only access the static member variables and member methods of the class. Because instance members are associated with specific objects! This need to understand, want to understand the truth, not memory!!! Because static methods are independent of any instance, static methods must be implemented, not abstract.

1.4 static code block

Static code blocks, also known as static code blocks, are static statement blocks independent of class members in a class. They can be multiple and can be placed anywhere. They are not in any method body. When loading a class, the JVM will execute these static code blocks. If there are multiple static code blocks, the JVM will execute them in order in which they appear in the class, Each code block is executed only once. For example:

public class Test5 { 
        private static int a; 
        private int b;
        static { 
                Test5.a = 3; 
                System.out.println(a); 
                Test5 t = new Test5(); 
                t.f(); 
                t.b = 1000; 
                System.out.println(t.b); 
        }
        static { 
                Test5.a = 4; 
                System.out.println(a); 
        }
        public static void main(String[] args) { 
                // TODO auto generate method stub 
        }
        static { 
                Test5.a = 5; 
                System.out.println(a); 
        } 
        public void f() { 
                System.out.println("hhahhahah"); 
        } 
}

Operation results:

3
hhahhahah
1000
4
5

Using static code blocks, you can assign values to some static variables. Finally, take a look at these examples. They all have a static main method, so that the JVM can call the main method directly without creating an instance.

1. What does static and final mean

static final is used to modify member variables and member methods, which can be simply understood as "global constants"!

For variables, it means that once a value is given, it cannot be modified and can be accessed through the class name.

For methods, the representation is not overwritable and can be accessed directly through the class name.

One particular issue to note:

For instance constants modified by static and final, the instance itself cannot be changed, but for instance variables of some container types (such as ArrayList and HashMap), the container variable itself cannot be changed, but the objects stored in the container can be modified, which is used a lot in programming. Take an example:

public class TestStaticFinal {
        private static final String strStaticFinalVar ="aaa";
        private static String strStaticVar =null;
        private final String strFinalVar = null;
        private static final int intStaticFinalVar = 0;
        private static final Integer integerStaticFinalVar =new Integer(8);
        private static final ArrayList<String>alStaticFinalVar = new ArrayList<String>();
        private void test() {
                System.out.println("-------------Before value processing----------\r\n");
                System.out.println("strStaticFinalVar=" +strStaticFinalVar + "\r\n");
                System.out.println("strStaticVar=" +strStaticVar + "\r\n");
                System.out.println("strFinalVar=" +strFinalVar + "\r\n");
                System.out.println("intStaticFinalVar=" +intStaticFinalVar + "\r\n");
                System.out.println("integerStaticFinalVar=" +integerStaticFinalVar + "\r\n");
                System.out.println("alStaticFinalVar=" +alStaticFinalVar + "\r\n");
                //strStaticFinalVar = "hahaha"// Error, final indicates the final state, and the variable itself cannot be changed
                strStaticVar = "Ha ha ha ha";               //Correct, static represents a class variable, and the value can be changed
                //strFinalVar = "hehe hehe"// Error, final represents the final state, and the initial value (even null) is required when defining. Once given, it cannot be changed.
                //intStaticFinalVar=2;                        // Error, final represents the final state, and the initial value (even null) is required when defining. Once given, it cannot be changed.
                //integerStaticFinalVar=new Integer(8);            // Error, final represents the final state, and the initial value (even null) is required when defining. Once given, it cannot be changed.
                alStaticFinalVar.add("aaa");       //Correct, the container variable itself has not changed, but the storage content has changed. This rule is very common and has many uses.
                alStaticFinalVar.add("bbb");       //Correct, the container variable itself has not changed, but the storage content has changed. This rule is very common and has many uses.
                System.out.println("-------------After value processing----------\r\n");
                System.out.println("strStaticFinalVar=" +strStaticFinalVar + "\r\n");
                System.out.println("strStaticVar=" +strStaticVar + "\r\n");
                System.out.println("strFinalVar=" +strFinalVar + "\r\n");
                System.out.println("intStaticFinalVar=" +intStaticFinalVar + "\r\n");
                System.out.println("integerStaticFinalVar=" +integerStaticFinalVar + "\r\n");
                System.out.println("alStaticFinalVar=" +alStaticFinalVar + "\r\n");
        }
        public static void main(String args[]) {
                new TestStaticFinal().test();
        }
}

The operation results are as follows:

-------------Before value processing----------

strStaticFinalVar=aaa

strStaticVar=null

strFinalVar=null

intStaticFinalVar=0

integerStaticFinalVar=8

alStaticFinalVar=[]

-------------After value processing----------

strStaticFinalVar=aaa

strStaticVar=Ha ha ha ha

strFinalVar=null

intStaticFinalVar=0

integerStaticFinalVar=8

alStaticFinalVar=[aaa, bbb]

After looking at the above example, it is much clearer, but it must be understood that the objects "loaded" in the container type variable modified by static final can be changed. This is very different from the general basic type and class type variables.

1.5 differences between Java static blocks and static methods

If some code must be executed when the project starts, you need to use static code blocks, which are actively executed; It needs to be initialized but not executed when the project is started. Without creating an object, it can be called by other programs and executed when called. This requires the use of static methods. This code is passively executed. Static methods are loaded when the class is loaded and can be called directly with the class name.

The difference between static code blocks and static methods is:

Static code blocks are automatically executed;

Static methods are executed when called

Static method: if we need a method that can be called without instantiating an object when programming, we can use the static method. The specific implementation is to add static in front of the method, as follows:

public  static  void method(){}

When using static methods, you should pay attention to the following aspects:

In a static method, you can only directly call other static members of the same class (including variables and methods), but you can't directly access non static members of the class. This is because for non static methods and variables, you need to create an instance object of the class before using them, while static methods do not need to create any objects before using them. (Note: static variables belong to the whole class, not to an object)

Static methods cannot reference this and super keywords in any way, because static methods do not need to create any instance objects before use. When static methods are called, the objects referenced by this are not generated at all.

Static block: when a class needs to execute a program when it is loaded, it can use static block.

1.6 summary

Sometimes you want to define a class member so that its use is completely independent of any object of the class. Normally, a class member must be accessed through the object of its class, but you can create a member that can be used by itself without referring to a specific instance. Such members can be created by prefixing the member declaration with the keyword static. If a member is declared static, it can be accessed before any object of its class is created without referring to any object. You can declare both methods and variables as static. The most common example of a static member is main(). Because main() must be called at the beginning of program execution, it is declared static.

Variables declared as static are essentially global variables. When an object is declared, a copy of the static variable is not generated, but all instance variables of the class share the same static variable. Methods declared as static have the following limitations:

  • They can only call other static methods.

  • They can only access static data.

  • They cannot reference this or super in any way (the keyword super is related to inheritance and is described in the next chapter).

If you need to initialize your Static variable by calculation, you can declare a Static block, which is executed only once when the class is loaded.

Keywords: Java Spring Boot Back-end

Added by libertyct on Tue, 04 Jan 2022 13:22:12 +0200