First, inherited initialization order
1. Initializes the parent class and initializes the subclass.
2. Executes the properties in the initialization object, and then executes the initialization in the constructor method.
Two, below, we use a simple example to illustrate this problem:
Parent class: Animal code:
Package Com.bluesky;
The public class Animal {public
Animal () {
System.out.println () is executed by the construction method of the animal class. ");
}
}
Subclass: Dog Code:
Package Com.bluesky;
The public class Dog extends Animal {public
Dog () {
System.out.println () is executed by the constructor of the subclass. ");
}
}
Testing class: Test code:
Package Com.bluesky;
public class Test {public
static void Main (string[] args) {
Dog Dog = new Dog ();
}
}
Execution results:
This shows that the parent class construction method is executed before the constructor method of the subclass is executed.
Now, let's take a little bit of code to see the order in which attributes and constructs are executed.
Parent class: Animal code:
Package Com.bluesky;
public class Animal {public
int age=10; If the constructor executes before the property executes, the value of the age should be:
//Because the subsequent assignment overrides the preceding assignment public
Animal () {
age=20; Similarly
System.out.println ("The construction method of the Animal class" was performed. ");
}
}
Subclass: Dog Class Code:
Package Com.bluesky;
public class Dog extends Animal {public
String name= "Jack"; If the constructor executes before the property executes, the value of name should be: Jack;
//Because the subsequent assignment overrides the preceding assignment public
Dog () {
name= "Rose";
System.out.println (the constructor of the subclass is executed.) ");
}
}
Testing class: Test code:
Package Com.bluesky;
public class Test {public
static void Main (string[] args) {
Dog Dog = new Dog ();
System.out.println ("dog.age=" +dog.age);
System.out.println ("dog.name=" +dog.name);
}
Run Result:
Summary: About the initialization order of inheritance in Java:
Initializes the properties of the parent class object, and then initializes the parent class's construction method.
Initializes the properties of the subclass object, and finally initializes the subclass's construction method.