When you create an instance of a class, follow these steps to create it:
1. Allocate space for all member fields of the current class and its parent, ancestor class, and give them default values
2. Start executing the constructor of the current class
3. If the current class has a parent class, create an instance of the parent class: Starting from step 2nd and treating the parent class as the new current class
4. Initialize the current instance and the field of the current instance
5. Executes the remaining code of the constructor for the current class.
The above steps contain a recursive algorithm. Suppose Class C has a parent class, and when you instantiate C to 3rd, you need to create an instance of the parent class, that is, the parent class will go through the 2nd, 3, 4, and 5 steps before Class C continues to step 4th. If the parent class also has its own parent class, the parent class is instantiated before the parent class executes step 3rd. And so on, until the object class is instantiated, because there is no parent class for the object class.
Here are two examples to illustrate.
Example 1
Public class Point { int x, y; = 1= 1;}}
Public class extends Point { int color = 0xff00ff;}
Public class Instancedemo { publicstaticvoid main () { new coloredpoint (); + "|" + cp.y + "|" + cp.color);} }
The result of creating an instance of the class is code new Coloredpoint (), the following is the procedure for instance creation:
1. Allocate memory to fields x, Y, color, and give them default values
2. The Coloredpoint constructor is called
3. Coloredpoint does not declare the constructor, it calls its default constructor:
Coloredpoint () {super ();}
4. The super () above actually refers to the parameterless constructor of point. The non-parametric constructor of point does not call the other constructors at the beginning, and the Java editor provides a constructor call that is inserted into:
Point () {super (); x = 1; y = 1;}
5. The super () above actually refers to the parameterless constructor of Object. Object does not have a parent class and is not inserted into the constructor. The parameterless constructor for Object does not have any side effects or return values. The constructor called is as follows
Object () {}
6. The field of point is initialized. Here, field X, Y does not have to be initialized.
7. The constructor for point is continued, which is assigned a value of 1 for x and Y, respectively. At this point, the parent-class point instantiation ends
8. The Coloredpoint field is initialized. Here, the field color is initialized to 0XFF00FF.
9. The Coloredpoint constructor is continued. Here, there is no other code inside the constructor, and no further execution is required. At this point, the Coloredpoint instantiation is complete.
(Example 2 to be continued:
Resources
12.5 Creation of New Class Instance, the Java Language specification, Java SE 8 Edition
Steps for [Java] instance creation