Static Static; can be used to modify class attributes methods code blocks
When we create a class, we are describing the appearance and behavior of the objects of that class. Unless it is new that creates an object of that class, you cannot actually get any object. Only when new is executed to create an object, the data storage space will be allocated and its methods can be called.
There are two situations that cannot be solved by the new object method.
1. If you just want to allocate a separate storage space in a specific domain, you don’t have to think about how many objects to create, or even create objects.
2. It is hoped that a certain method is not associated with any object of the class that has this method.
In other words, there is no need to create an object to call this method. At this time, we can use the static keyword to solve it.
When declaring an object to be static, it means that this field or this method will not be associated with any object of its class. Therefore, we can call static methods or access static fields without creating any object of this class.
static attribute [class attribute]: an attribute shared by all objects of this class, which will only occupy a piece of memory space
For example:
Java code
public class one{ static i=10; }
Now, even if you are re-creating two one objects, one .i also has only one storage space, and these two objects will share this i at the same time
Java code
one a1=new one(); one a2=new one();
Here, a1 and a2 both point to the same storage space, so their values are both 10.
static Method [class method]: Class methods can no longer use this and super to represent objects. Whether a class method calls the parent class or is overridden by a subclass is only related to the class name. For example:
Java code
public class two{ static void jia(){ one.i++; }
Now, this two The jia() method increments the static data i through the ++ operator.
We can call it with a typical new object:
Java code
two t=new two(); t.jia();
Because this method is static, we can call it directly, such as:
Java code
two.one();
An important usage of the static method is not to You can call it by creating any object.
static code block: also called static code block, it is a static statement block in a class that is independent of class members. There can be multiple and can be placed anywhere. It is not in any method body. The JVM will execute these static statements when loading the class. If there are multiple static code blocks, the JVM will execute them in the order they are written in the class, and each code block will only be executed once.
For example:
Java code
public class dome{ static { System.out.print("A"); } static { System.out.print("B"); } static { System.out.print("C"); } public static void main(String[] args) { System.out.print("E"); } }Execution result
ABCE