In this section, we say how the constructor is loaded in memory.
As we said before, the constructor is called only once when the object is created. So what is the change in memory in the process of creating an object?
We proceed to the last section of the person class, and we analyze
Class person{private String name;private int age; The person ()//constructor, respectively, the member variable name and age assign a fixed value {name = "Baby"; age = 1; SYSTEM.OUT.PRINTLN ("person Run");} Person (String N)//constructor, with an initial name parameter {name = n;} Person (String N,int a) {name = N;age = A;} public void Speak () {System.out.println (name+ ":" +age);}}
We use the following two lines of code to analyze the loading process of the constructor in memory
Class Consdemo{public static void Main (string[] args) {person p = new person ("Xiao Qiang", ten);p. Speak ();}}
For the above test, we analyze its running process:
1.main method into the stack memory, the main method has a person class type variable p;
2.new creates a person object and creates a space in heap memory (if the address is 0x0045), there are two member variables name and age in the space;
3. Initialize the two member variables of the object, at which time the call constructor person (String N,int a) is automatically selected;
4. Constructor person (String N,int a) into the stack memory, and have parameters n= "Xiao Qiang", a=0;
5. Then initialize the values of the parameters N and a in the heap memory with the name and age variables, and the initialization of the object is completed;
6. Assign the address 0x0045 to the variable p in the Main method;
7. Constructor person () out stack, release parameters n and A;
8. Execute the P.speak () statement, call the Speak () method in the person class, then speak the method into the stack;
9. Execute the PRINT statement, jump out of the Speak method, speak method out of the stack;
10. Jump out of the main method, the main method out of the stack, the program runs the end.
We analyzed a simple object creation process above, and simply learned how to load and run the constructor in memory, where the initialization of the object is highlighted, and if the constructor is not defined in the class, we call the default constructor when we create the object, and when we define the constructor, The object is initialized by selecting a different constructor from the parameter type, and we know that the object must be initialized, and the constructor is called to initialize, so the constructor must be in the stack memory.
[Javase Learning note]-7.4 The memory load of the constructor