1. Objects that can be decorated are: variables, methods, blocks of code
The corresponding is: Static variable/class variable; static method; static code
Eg: public class student{
public static int a = 0;
public static int GetValue () {
return A;
}
}
2. Anything that is modified by static is class-level, and all objects are shared together
See Example:
1 Public classUser {2 Private Static intUsernumber = 0 ;3 4 PublicUser () {5Usernumber + +;//add 1 for each object you create6 }7 8 Public Static voidMain (string[] args) {9User user1 =NewUser ();//at this point the Usernumber is 1TenUser user2 =NewUser ();//at this point the Usernumber is 2 One ASystem.out.println ("User1 usernumber:" +user.usernumber); -System.out.println ("User2 usernumber:" +user.usernumber); - } the } ------------- - Output: -User1 Usernumber:2 +User2 Usernumber:2View Code3. You can access it directly with the class name, without having to instantiate an object for use.
Eg: student.getvalue ();//Direct class name call
or Student s = new Student ();
S.getvalue ();//can also be invoked by the instance of Mr., but the first recommended
4. Use static to be aware of
4.1. Static variables must be initialized when they are defined , and the initialization time is earlier than non-static variables.
4.2. Static modified method, you can only call a static variable or method, and you cannot call a variable or method that is not static.
4.3. cannot refer to this, super in any form. (because they are not static.)
Summary: Whether it is a variable, a method, or a block of code, as long as the static decoration, is when the class is loaded, it is "ready", that is, can be used or has been executed, can be executed from the object.
Conversely, if there is no static, you have to rely on the object instance, Remember two points, usually static only two meaning, the rest / share
Reference : Very detailed here
The Static keyword for Java