When there is an inheritance relationship between multiple classes, creating a subclass object causes the parent class to initialize the execution of the block.
The execution order is: Initialize the static initialization block of the parent class (the highest level) first, the parameterless constructor of the parent class, the static initialization block of the subclass, the parameterless constructor of the subclass,
Then is the normal initialization block of the parent class, the normal initialization block of the subclass, the parameter constructor of the parent class, and the parameter constructor of the subclass.
For example:
Package inheritance;classroot{Static{System. out. println ("static initialization block of root"); } {System. out. println ("common initialization block for root"); } PublicRoot () {System. out. println ("The parameterless constructor of root"); }}classMid extends root{Static{System. out. println ("static initialization block for mid"); } {System. out. println ("normal initialization block for mid"); } PublicMid () {System. out. println ("parameter-free constructors for mid"); } PublicMid (String msg) {//calling overloaded constructors in the same class through this This(); System. out. println ("with parameter constructors for mid, the parameter values are:"+msg); }}classLeaf extends mid{Static{System. out. println ("static initialization block of the leaf"); } {System. out. println ("ordinary initialization blocks of the leaf"); } PublicLeaf () {//A constructor that invokes a string argument in the parent class through SuperSuper"Java Initialization Sequence demo"); System. out. println ("the constructor that executes the leaf"); }} Public classTeststaticinitializeblock { Public Static voidMain (string[] args) {NewLeaf (); }}
Results:
Example::::::::::::
Packageclass and inheritance; Public classTest { Public Static voidMain (string[] args) {NewCircle (); } } classDraw { PublicDraw (String type) {System.out.println (type+ "Draw Constructor"); } } classShape {PrivateDraw Draw =NewDraw ("Shape"); PublicShape () {System.out.println ("Shape Constructor"); } } classCircleextendsShape {PrivateDraw Draw =NewDraw ("Circle"); PublicCircle () {System.out.println ("Circle Constructor"); } }
This topic focuses on the sequence of calls and initialization of constructors at class inheritance. One point to remember is that the constructor invocation of the parent class and the initialization process must precede the child class . Because the Circle class's parent class is a shape class, the Shape class initializes first and then executes the constructor of the shape class. Then the sub-class circle is initialized, and the last circle's constructor is executed.
Results:
Java Multiple class inheritance