Before we get started on static, I want to show you some interesting code:
public class Test {
static{
System.out.println("test static 1");
}
static{
System.out.println("test static 2");
}
public static void main(String[] args) {
}
}
Copy the code
After seeing the program, white boy shoes hair: what trifle? There’s nothing in the main method. What can I run? Blogger you star star…
Result: teststatic 1
test static 2
Copy the code
White shoes: What… That what… Blogger what did I say? I didn’t say anything…
In fact, the above code to understand the natural understand, do not understand the natural do not understand, because the above code involves the JVM class loading! It is certainly outside the scope of this blog post, but if you are interested in understanding the above program, this article may be helpful
This article will give you an in-depth understanding of Java class loading and ClassLoader source code analysis.
1. Static
The main meaning of static is to create domain variables or methods that are independent of concrete objects. So that you can use properties and call methods without creating objects!
Another key use of the static keyword is to form static blocks of code to optimize program performance. Static blocks can be placed anywhere in a class, and there can be more than one static block in a class. When the class is first loaded, each static block is executed in the same order as the static block, and only once.
The static block can be used to optimize program performance because it is executed only once when the class is loaded. As a result, many times initialization operations that only need to be done once are placed in static code blocks.
2, Static
1. Static variables or methods are independent of any object of the class. That is, they do not belong to any instance object, but are shared by instance objects of the class.
What do you mean by “shared by instances of a class”? That is, a static member of a class that belongs to everyone. All class objects are shared, unlike member variables that are self-contained… I think I’ve made it very colloquial, you see?
When the class is first loaded, the static part is loaded and initialized only when the class is used for the first time.
Static variable values are allocated at class load time and are not reallocated when class objects are created. If you assign, you can assign anything!
4. Static variables or methods take precedence over objects. That is, when a class is loaded, it can be accessed even if no object has been created.
3. Static application scenarios
Since static is shared by instance objects of the class, if a member variable is shared by all objects, it should be defined as a static variable.
Therefore, the most common static application scenarios are:
1, modify member variable 2, modify member method 3, static code block 4, modify class [can only modify inner class that is static inner class] 5, static guide package
The above application scenarios will be covered later…
4. Concepts of static and instance variables
Static variables: Static modified member variables are called static variables. Static variables belong to the class, not the object.
Instance variables: Member variables that are not modified static are called instance variables, and instance variables are instance objects that belong to the class.
One more thing to note: Static is not allowed to modify local variables, don’t ask me what to ask, because Java rules!
5, static variables and instance variables
Static variables: Static variables are classes that do not belong to any instance objects, so they only have one copy in memory. The JVM allocates memory for static variables only once during class loading.
Instance variables: Each time an object is created, it will allocate memory space for member variables for each object. Instance variables belong to instance objects. In memory, there are several copies of member variables when objects are created several times.
I believe everyone IQ is higher than Yichun IQ, should be able to understand the above words. The following examples are completely out of entertainment, understand the need not see, the following example is for reference only, only for entertainment under the atmosphere, catch time bear DEI can be skipped!
How do you understand that? An analogy… For example, programmer Wang is a more gentle and sunny boy, the day of 1024, the boss idle nothing, must pull programmer Wang to play, how to play? Boss and xiao Wang one person holding a kitchen knife, the rule is very simple, hurt each other, one person a knife, you a knife, I a knife…. At the beginning of the game, the boss said nothing, jump up is a knife, programmer Wang did not say anything backhand is a kitchen knife back, this time the boss mad, eyes staring te big, jump up is a knife, this time programmer Wang dare not fight back, did not start. Did not think of the boss more and more fierce, left a knife right a knife whole journey down almost cut a half…. Programmer Wang has not returned the hand, because Wang knows he is the boss…
The programmer wang will only sword, for the first time in the boss, the boss back knife, then don’t strike back, this time we put the programmer wang as static variables, the boss for the first time to wang flick knife as class loading, suggests wang back to the boss a knife is allocated memory space, and one knife this round process as the class loading process, Each subsequent cut by the boss is treated as creating an object.
Static variable values are allocated when the class is first loaded and are not reallocated when the class object is created
After the boss got a knife lay a hospital for a year, after a discharge back to the company the first thing to do is to pull the programmer yichun come out to play, but the boss, the blogger programmers yichun abnormal personality, violent, the boss handed programmers yichun a kitchen knife, a blogger yichun took the chopper, jumped off guard by the boss is a knife, the programmer of yichun ao, in pain Irascible programmers yichun haven’t ao, jumped at the same time of ao is to give the boss a knife, and then the boss jumped up another knife, programmers yichun ao is back with a knife, the boss jumped up another knife, programmers yichun ao is back with a knife, as long as the boss didn’t stop programmers yichun didn’t stop, because programmers yichun know, his temper, this Irascible rise SI all dare to touch, affirmation have a few old iron know….
Programmer yichun is similar to instance variables, each time to create an object, will allocate memory space for each object member variables, just like the boss to a knife, programmer Yichun will return a knife this way…
Two ways to access static and instance variables
We all know that static variables belong to this class, not objects. Static is independent of objects.
But you have not thought: static member variables although independent of the object, but does not mean that can not be accessed through the object, all static methods and static variables can be accessed through the object [as long as the access permission is enough to allow the line], do not understand it, to a code to understand
public class StaticDemo {
static int value = Awesome!;
public static void main(String[] args) throws Exception{
new StaticDemo().method();
}
private void method(){
int value = 123;
System.out.println(this.value); }}Copy the code
Guess what, I’m guessing your answer is 123, huh? Actually,
Running results:Awesome!
Copy the code
Go back and savor the above paragraph again, you can be very objective and clear, this concept should have just this kind of usage is not recommended!
So let’s summarize the two ways to access static and instance variables:
Static variables:
Class name. Static variable
Static variables (not recommended)
Static method:
Class name. Static method
Static methods (not recommended)
7, static method
The main method is a static method, and the main method is a static method. A static method does not belong to any object, so this is the current object.
One more thing: constructors are not static methods!
Static code block
Static block BaseThree — > BaseTwo — > BaseOne static block BaseThree — > BaseTwo — > BaseOne
BaseOne class
package com.gx.initializationblock;
public class BaseOne {
public BaseOne() {
System.out.println("BaseOne Constructor");
}
{
System.out.println("BaseOne initialization Block");
System.out.println();
}
static {
System.out.println("BaseOne Static Initialization Block"); }}Copy the code
BaseTwo class
package com.gx.initializationblock;
public class BaseTwo extends BaseOne {
public BaseTwo() {
System.out.println("BaseTwo constructor");
}
{
System.out.println("BaseTwo initialization block");
}
static {
System.out.println("BaseTwo Static Initialization block"); }}Copy the code
BaseThree class
package com.gx.initializationblock;
public class BaseThree extends BaseTwo {
public BaseThree() {
System.out.println("BaseThree constructor");
}
{
System.out.println("BaseThree initialization block");
}
static {
System.out.println("BaseThree Static Initialization block"); }}Copy the code
Test demo2 class
package com.gx.initializationblock;
/ * note: In inheritance, the static block of parent class A is executed first, the static block of parent class B is executed, and the static block of parent class B is subclassed finally, and then the non-static block and constructor of parent class A are executed. This is followed by class B's non-static blocks and constructors, and finally the subclass's non-static blocks and constructors */
public class Demo2 {
public static void main(String[] args) {
BaseThree baseThree = new BaseThree();
System.out.println("-- -- -- -- --");
BaseThree baseThree2 = newBaseThree(); }}Copy the code
The results
BaseOne static initialization block BaseTwo Static initialization block BaseThree Static initialization block BaseOne initialization block BaseTwo initializer block BaseThree Initializer block BaseThree constructor ----- BaseOne initialization block BaseOne constructor BaseTwo initialization block BaseTwo constructor BaseThree Initialization block BaseThree constructorCopy the code
Static code blocks and the order in which they are executed
Static code blocks are usually used to initialize static variables, such as defining enumerated classes, as follows:
public enum WeekDayEnum {
MONDAY(1."On Monday"),
TUESDAY(2."Tuesday"),
WEDNESDAY(3."On Wednesday"),
THURSDAY(4."Thursday"),
FRIDAY(5."Friday"),
SATURDAY(6."Saturday"),
SUNDAY(7."Sunday");
private int code;
private String desc;
WeekDayEnum(int code, String desc) {
this.code = code;
this.desc = desc;
}
private static final Map<Integer, WeekDayEnum> WEEK_ENUM_MAP = new HashMap<Integer, WeekDayEnum>();
// Initialize the map
static {
for (WeekDayEnum weekDay : WeekDayEnum.values()) {
WEEK_ENUM_MAP.put(weekDay.getCode(), weekDay);
}
}
public static WeekDayEnum findByCode(int code) {
return WEEK_ENUM_MAP.get(code);
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
} 
Copy the code
Not only enumerations, of course, but the familiar singleton pattern also uses static code blocks, as follows:
public class Singleton {
private static Singleton instance;
static {
instance = new Singleton();
}
private Singleton() {}
public static Singleton getInstance() {
returninstance; }}Copy the code
9. Static variables are different from ordinary variables
Static variables are also called static variables. The difference between static and non-static variables is that static variables are shared by all objects and have only one copy in memory, which is initialized if and only if the class is first loaded. Non-static variables are owned by the object, initialized when the object is created, and have multiple copies that do not affect each other.
Also, static member variables are initialized in the order they are defined.
Static inner classes
One of the biggest differences between a static inner class and a non-static inner class is that a non-static inner class implicitly stores a reference to the enclosing enclosing it after compilation, whereas a static inner class does not. The absence of this reference means:
1. Its creation does not depend on the creation of the enclosing class. 2. It cannot use non-static member variables and methods of any enclosing class.
Code examples (static inner classes implementing the singleton pattern)
public class Singleton {
Declare it private to avoid calling the default constructor to create an object
private Singleton() {
}
// Declaring it private indicates that the static inner class can only be accessed within the Singleton class
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getUniqueInstance() {
returnSingletonHolder.INSTANCE; }}Copy the code
When the Singleton class is loaded, the static inner class SingletonHolder is not loaded into memory. SingletonHolder is loaded only when the getUniqueInstance() method is called, triggering SingletonHolder.instance. And the JVM can ensure that INSTANCE is instantiated only once.
This approach not only has the benefit of delayed initialization, but also provides thread-safe support by the JVM.
11, static guide package
Static package guide format: import static
These two keywords can be used together to specify the import of specified static resources in a class, and static member variables and member methods of the class can be used directly instead of using the class name
// Math. -- Import all static resources in Math. You can use static methods instead of calling them by class name
// If you want to import a single static method, just replace it with the corresponding method name
import static java.lang.Math.;
// import static java.lang.math.max; It has the same effect
public class Demo {
public static void main(String[] args) {
int max = max(1.2); System.out.println(max); }}Copy the code
Static packages can save a bit of code when writing code. You can call the static members of the package directly, but it will affect the readability of the code, so it is generally not recommended to use it in development.
12. Static Notes
1. Static access can only be static. 2. Non-static can access both non-static and static.
The lotus root is still final and static
Static static static static static static static static static static static static static static static static static static static static
package Demo;
class FinalDemo {
public final double i = Math.random();
public static double t = Math.random();
}
public class DemoDemo {
public static void main(String[] args) {
FinalDemo demo1 = new FinalDemo();
FinalDemo demo2 = new FinalDemo();
System.out.println("Final I =" + demo1.i);
System.out.println("Static modified t=" + demo1.t);
System.out.println("Final I =" + demo2.i);
System.out.println("Static modified t=" + demo2.t);
System.out.println("t+1= "+ ++demo2.t );
// System.out.println( ++demo2.i ); // Failed to compile
}
}
运行结果:
final修饰的 i=0.7282093281367935
staticModification of t =0.30720545678577604Final modifier I =0.8106990945706758
staticModification of t =0.30720545678577604
t+1= 1.307205456785776
Copy the code
Static variables do not change because static applies to member variables only to indicate that a copy is saved and that it does not change. What do you make of this copy? The static modifier is initialized when the class is loaded, and it is initialized only once.
And the final modifier has changed, right? Does that change your view of final? The blogger has also prepared an article. Programmer, do you really understand the final keyword?
Ok, this is the end of the article, I hope this article can help you to understand static, if there is insufficient or improper, I hope you understand and welcome criticism and correction!
If this article is helpful to you, even a little bit, please give a thumbs up. Thank you
Reference: Java Programming Ideas baijiahao.baidu.com/s?id=160125… Blog.csdn.net/qq_34337272… www.cnblogs.com/dolphin0520…
Finally, welcome everyone to pay attention to my public number, discuss technology together, yearning for technology, the pursuit of technology