In the Java programming language, the initialization of objects is very structured, and this is done to ensure security. In the previous module, you saw what happened when a particular object was created. Because of inheritance, objects are completed, and the following behaviors occur sequentially:
- The storage space is allocated and initialized to a value of 0
- To perform an explicit initialization
- Call construction method
- Each class in the hierarchy takes the last two steps, starting at the top.
The Java technology security model requires that all aspects of an object that describes a parent class must be initialized before the subclass executes anything. Therefore, the Java programming language always calls the version of the parent class construction method before the child constructor method is executed. When you run an inherited class, be sure to remember that initializing the subclass must first initialize the parent class, which is a basic running procedure for the Java program. Like what:
1. Public class Test extends Parent {
2. Private String name;
3. private int age;
4. Public Test () {
5. Name= "Tom";
6. age=20;
7.}
8. public static void Main (string[] args) {
9. Test T = new Test ();
System.out.println (T.name + "age is" + t.age);
11.}
12.}
Class Parent {
private int num = 1;
. Public Parent () {
System.out.println ("Now initializes the parent class");
17.}
public void Test () {
System.out.println ("This is the test method of the parent class");
20.}
21.}
The basic sequence of operations for the above classes is:
- First, run to line 8th, which is the entrance to the program.
- Then run to line 9th, where a new test is called to call Test's construction method.
- Run To Line 4th, note: The initialization subclass must first initialize the parent class.
- To initialize the parent class first, run to line 15th.
- Then the 14th line, initializing a class, must first initialize its properties.
- And then the 16th line.
- Then the 17th line indicates that the parent class initialization is complete.
- Then it goes back to the subclass and starts initializing the property, so it runs to line 2nd and then line 3rd.
- After the subclass property is initialized, the constructor of the subclass is returned, and the code inside is executed, which is the 5th, 6 line.
- Then the 7th line indicates that the new Test instance is complete.
- Then go back to the main method and execute line 10th.
- And then the 11th line.
Initialization order of parent class and subclass in 3.Java inheritance