2018-05-01
Subclass Initialization Process
The constructor's invocation follows the following order:
(1): Call the base class constructor. This step is repeated recursively, first of all to construct the root of this hierarchy, then the next layer of the export class, and so on, until the lowest layer of the export class.
(2): The initialization method of the member is called in the order of Declaration.
(3): invokes the principal of the derived class constructor. (that is, the contents of the main method in the article)
The ultimate goal: to have all member variables in the method initialized.
The parent class object is created before the child class object is created
Before the subclass constructor is called, the constructor of the parent class is called before the subclass constructor, and the parameterless constructor is called by default
If the parent class does not have a constructor that can be called by the class (the parent class has all the state and behavior searched with the private adornment), there is no subclass. (In fact, this situation basically does not exist)
If the parent class does not provide an argument-free constructor, the subclass must display a constructor that invokes the parent class with parameters through the Super statement. (See picture)
code example:
//Animalclassanimal{PrivateString name; Private intAge ; Animal (String name,intAge ) {System.out.println ("Animal Builder"); This. Name =name; This. Age =Age ; } PublicString GetName () {returnname; }}//FishclassFishextendsanimal{PrivateString color;//ColorFish (String name,intAge , String color) { Super(Name,age);//The call constructor is displayed, super calls the parent class constructor, and must be placed in the first sentence of the subclass constructor. This. color =color; //super ();//implicit invocation of the parent class of the current object without a parameter construction method } Public voidsay () {System.out.println (GetName ()+ "," + This. color); }}//Subclass Initialization ProcessclassSubclassinitdemo { Public Static voidMain (string[] args) {//Create a Fish objectFish f =NewFish ("Goldfish", 5, "Red"); F.say (); }}
Output Result:
Animal Construction Device
Goldfish, Yellow
Ii. Java Object-oriented (8) _ Inheritance thought--subclass initialization process