Click to enter _ more _java thousand ask
1. What is the use of static?
Static is the key word for Java, which is used for static purposes. The so-called static, which can be used after the program is compiled, does not need to create any instances. Static can modify classes, methods, variables, and class code blocks, as follows:
static Method
The method that is declared by Static is called a static method and does not need to instantiate the object directly from the class name, most commonly, main ().
See the Main method here: What is the Main method
For example:
publicclass TestStatic { publicstaticvoidmain(String[] args) { TestStatic.testStatic(); } publicstaticvoidtestStatic() { System.out.println("my testStatic"); }}
The results of the operation are as follows:
My teststatic
static Property
Properties declared by static are called static properties (class variables) and do not require instantiation of objects to be used directly from the class name.
Learn about instance variables, class variables here: What is the difference between local variables, class variables, and instance variables
For example:
publicclass TestStatic { publicstaticvoidmain(String[] args) { "staticString"; System.out.println(TestStatic.staticString); } publicstatic String staticString;}
The results of the operation are as follows:
Staticstring
Static code block
A block of code that is modified by static is executed when the class is loaded, for example:
publicclass TestStatic { publicstaticvoidmain(String[] args) { } static { System.out.println("my static code"); }}
The results of the operation are as follows:
My static code
STAITC class
Normally, it is not possible to modify a class with static. If you must modify the class with static, you can only decorate the inner class. If you want to use the STATITC property or method in an inner class, you need to use the static inner class (normal inner classes can only use static final), for example:
publicclass TestStatic { static class StaticA { privatestatic"my str"; publicstaticgetStr() { return str; } } publicstaticvoidmain(String[] args) { System.out.println(TestStatic.StaticA.getStr()); }}
The results of the operation are as follows:
My str
Java thousand ask _03 Basic grammar (017) _static What's the use