About the instantiation process of an object:
1. Check whether the class is loaded, load the class if it is not loaded, and load all parent classes;
Lazy load (load on Demand): If you use the load for the first time, just load it. The path made by Classpath to find the class file (. Class) is an object after loading, and the type is class. Get this class object: student.class-->class instance
2. Allocate object space in the memory heap. Recursively allocates all parent classes and child class property spaces. Father Type Subtype, the property is automatically initialized by default. Automatically initialized to "0" value;
3. Assigning values to the property;
4. Recursively invokes the parent class builder. (The default invocation of the parent class parameterless constructor);
5. Call this class Builder
In fact, there are many similar questions in the interview process, the test is the order of initialization, first of all to clarify the following concepts:
1. Static initialization refers to the execution of static initialization block inside the content;
2. Instance initialization refers to the contents of the execution instance initialization block;
3. Construction method: A name is the same as the name of the class method, especially with no return value;
Give the following code to facilitate understanding:
public class Testinstanceinit {
public static int n = 0;//static variable
static {//This is a statically initialized block
Print ();
System.out.println ("This is static block");
}
{//Instance initialization block
SYSTEM.OUT.PRINTLN (n);
}
Public Testinstanceinit () {//Construction method
System.out.println ("This is Testinstanceinit ' s constructor~");
}
public static void print () {//static method
System.out.println ("This is static method~");
SYSTEM.OUT.PRINTLN (n);
n + 1;
}
public static void Main (string[] args) {
New Testinstanceinit ();
}
}
Console output Results:
This is static method~
0
This are static block
1
This is Testinstanceinit ' s constructor~
If there is a variable how to deal with it:
public class Testinstanceinit {
static variables
public static String Staticfield = "static variable";
Variable
Public String field = "Variable";
Static initialization block
static {
System.out.println (Staticfield);
SYSTEM.OUT.PRINTLN ("Static initialization Block");
}
Initializing blocks
{
System.out.println (field);
System.out.println ("initialization block");
}
Construction device
Public Testinstanceinit () {
System.out.println ("constructor");
}
public static void Main (string[] args) {
New Testinstanceinit ();
}
The console output results:
static variables
Static initialization block
Variable
Initializing blocks
Construction device
Summarized as follows:
Order of execution
(static variable, static initialization block) > (variable, initialization fast) > constructor
The sequence of static and static initialization fast/variable and initialization depends on the order in which they appear in the class