Java basics-Use of static keywords, java-static keywords
I. Functions of static keywords
Make the class members completely independent from any objects of the class. Generally, a class member must be accessed through its class object, but the static modified member can be accessed by itself without referencing a specific instance.
Once a member is declared as static, it can be accessed before any object of its class is created without referencing any object.
A variable declared as static is essentially a global variable. when an object is declared, it is not a copy of The stitc variable, but a static variable shared by all instance variables of this class.
Methods declared as static have the following restrictions:
1. They can only call other static methods;
2. They can only access static data;
3. They cannot reference this and super in any form
If you need to initialize your static variable through calculation, you can declare a static block, which is only executed once when the class is loaded.
The following example shows that the class has a static method, some static variables, and a static initialization block:
// Demonstrate static variables,methods,and blocks.class UseStatic { static int a = 3; static int b; static void meth(int x) {System.out.println("x = " + x);System.out.println("a = " + a);System.out.println("b = " + b); } static {System.out.println("Static block initialized.");b = a * 4; } public static void main(String args[]) {meth(42); }}
Once the UseStatic class is loaded, all static statements are run. First, a is set to 3, then static block execution (print a message), and finally B is initialized to a * 4 or 12. Then, call main () and main () to call meth () and pass the value 42 to x. The three println () Statements reference two static variables a and B, and the local variable x.
Call static member variables
Class Name. static modified Member