static

Class members fall into two categories: static members and instance members. Static members belong to classes; Instance members belong to objects, that is, instances of classes.

What does that mean?

Java divides memory into stack memory and heap memory. The stack memory is used to hold some basic types of variables, arrays, and object references, while the heap memory mainly holds some objects. When the JVM loads a class that has static modified member variables and methods, it creates a fixed size area of memory for those member variables and methods in a fixed location, making them easily accessible by the JVM. Also, if static member variables and methods are not scoped, their handles remain unchanged. And static means that it is unrecoverable. That is, if you change a place, it doesn’t change back. If you clean it up, it doesn’t come back.

So, static modifiers belong to classes, and a chunk of memory is created to hold them when the class is loaded, and the static content in any new object is the same.

What does static modify?

  1. Static variables are called static variables. In Java, there is no such thing as a global variable, so we can declare a static variable to implement the function of a global variable.

  2. Static methods. Likewise, static methods are created when the class is loaded, independent of the instance object, so static methods cannot be abstract and must be implemented. We access them by accessing the class name.

  3. Blocks of code are created as the class is loaded, and can generally be used to perform some operations ahead of time, allowing for singleton patterns

Static and thread safety

Does multithreading affect static members? It is important to understand the premise of thread insecurity: multiple threads operating on the same memory area without any protection

So we just need to know that when we use multiple threads, we can share the same memory. Static members create a fixed memory space when the class is loaded, so when we use multiple threads to access static variables, we can have thread unsafe.

When we use static methods, we run the same in-memory methods, but we don’t have thread-safety problems if the variables we operate on inside static methods are local variables (each thread calls a new one and doesn’t share a memory region).

conclusion

Since static members are prepared in advance when the class is loaded, they belong to the class, so when we call static methods or code blocks, we can only call static methods and static variables. We can’t refer to member variables, this, super, etc.