Today, I read an interesting article on the initialization sequence of Java object instances in dzone.Article. It is interesting because the author uses a slightly less recommended encoding style. Only this encoding style can trigger this rare Java object initialization order problem.
In fact, the initialization sequence of Java objects is a relatively Basic Java knowledge point. However, most of the articles on the Internet are unclear, and problems may occur if you are not careful when using them.
Therefore, in this article, I want to analyze the problem by combining the JLS and my own understanding.
Okay. Let's take a look at a simple example of imitating the original intention of dzone:
Package com. kenwublog. tmp;
Public Class A extends B {
Public int A = 100;
Public (){
Super ();
System. Out. println ();
A = 200;
}
Public static void main (string [] ARGs ){
System. Out. println (new A (). );
}
}
Class B {
Public B (){
System. Out. println (a) This). );
}
}
ExampleCodeIt's very simple. I don't want to explain it much. Let's look at the output directly:
0
100
200
Compare this output to analyze the initialization sequence of the object in detail:
1. allocate memory space for Class A. Initialize all member variables as default values, including the primitive type (Int = 0, Boolean = false ,...) And reference type.
2. Call the Class A constructor.
3. Call Class B constructor.
4. Call the object empty constructor. (The Java compiler adds this constructor by default, and the object constructor is an empty function, so it returns immediately)
5. initialize class B member variables. skip this step because Class B does not have member variables.
6. Run the sysout command to output the member variable A of subclass. // 0 at this time
7. initialize the Class A member variable and assign a value of 100 to the small class A member variable.
8. Run sysout to output a smaller member variable of the current Class. // 100 at this time
9. assign a value to the member variable of the current class A as small as 200.
10. Run sysout in the main function, and the member variable of the output class A instance is. // 200 at this time
The bold description of the two lines is the focus, and the conclusion is that after the parent class constructor is called, the value of the member variables is the default value.
The author dzone is planted here, without carefully analyzing the sequence of member variable initialization in object initialization, resulting inProgramNot executed as intended.
In fact, this type of problem is familiar with the principle that, on the one hand, as long as too many business logic is inserted in the constructor, the probability of a problem will be much lower.
from: http://news.bangkaow.com/news/20110623/194720.html