It is important to be clear about static, and it is easy to make a variety of mistakes if used carelessly.
(1) For example: if the definition of a global variable A is static, when testing the code more than once, the previous run test to get a value of a will affect the next test results, so that the results of multiple tests will result in error, so try not to be the class in the need to be assigned multiple variables are defined as static.
(2) When using the static modifier function, if you want to use a global variable, you must define the global variable as static, because the static function can only access static variables and cannot access non-static variables. In this case there will be a null pointer exception, so be careful when you use it!
(3) A member variable or method that is modified by static is independent of the object of that class, so long as the class is loaded, it can be accessed before object creation is instantiated .
- static variables
Variables that are modified by static are static variables, and when the JVM loads the class, it can be accessed directly through the class name, and all instances of the class share a static variable .
- Static methods
Static methods can be called directly through the class name, but cannot directly access the instance variables and methods of the owning class, only the static variables and methods of the owning class , because instance members are associated only with specific objects.
- Static code block
A static block of statements that is independent of a class member in a class, not in any method body, and when the JVM loads the class, it executes a code block without waiting for instantiation , the static statement blocks can be multiple, and the JVM executes sequentially in their order.
(4) Normally static and final are used together to define invariant variables. For example, the following situation:
1 Public Static Final intCenter_order=0;2 Public Static Final intCenter_random=1;3 Public Static Final intmax_attempts=4000;4 Public Static Final Doublemin_criteria=1.0;5 Public Static Final Doublemin_euclideandistance=0.8;
Static problem in Java