The difference between static variable static code block static method non-static variable non-static method in Java

Static variables: When the class is loaded, static variables are loaded. Also called global variables. Can be used directly without instantiation (new class).

Static code block: Some code must be executed when the project is started , this code is actively executed ( when the class is loaded, the static code block is executed, and only executed once, static blocks are often used to execute class attributes. initialization )

Static method: It needs to be initialized when the project is started. In the case of no object creation , this code is executed passively ( static method is already loaded when the class is loaded and can be called directly with the class name )

What both have in common: when the class is loaded, both are loaded .

The difference between the two: static code blocks are executed automatically; static methods are executed when they are called. 


When using static methods of a class, note:

a. In a static method, you can only directly call other static members (including variables and methods) in the same class, but cannot directly access non-static members in the class ( this is because, for non-static methods and variables, you need to create a class first The instance object can only be used after the static method is used without creating any object )

b.  A static method cannot refer to the this and super keywords in any way, because the static method does not need to create any instance object before using it. When the static method is called, the object referred to by this is not generated at all.

c. Static variables are variables that belong to the entire class rather than to an object. Note that you cannot declare any variable inside the method body as static


1: The loading order of the class through the class loader: first load the static variable of the parent class -> load the static variable of the child class, load and execute the content of the static code block of the parent class -> load and execute the content of the static code block of the child class -> will The parent class static method is loaded into the memory (jvm method area) -> the subclass static method is loaded into the memory (jvm method area) 

When instantiating an object (new), if it is the first time, it should execute 1 first (using the class for the first time), and then load the non-static variables and methods of the parent class -> load the non-static variables and methods of the subclass (directly in the heap) establish a memory address). After that, whenever a variable is instantiated, only non-static variables and methods should be loaded directly (the memory address is established directly in the heap)


Guess you like

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