Home >Java >Javagetting Started >When creating a derived class object, what is the execution order of constructors?
When creating a derived class object, the execution order of the constructor is: base class constructor, derived class object member constructor, and the constructor of the derived class itself. When an object is created, the code loading order is: static code, non-static code, and constructor methods.
When creating a derived class object, the execution order of the constructor is: base class constructor, derived class object member constructor, and the constructor of the derived class itself.
(Recommended tutorial: java introductory program)
Detailed introduction:
The loading order of the code when the object is created is: static code --> Non-static code --> Constructor.
If the parent class is inherited, the loading order is: the static code of the parent class --> the static code of the subclass --> the non-static code within the parent class --> the parent class's Constructor --> Non-static code of the subclass --> Constructor of the subclass.
Among them, static code includes (static methods, static variables, static code blocks, etc.), non-static code is (member methods, member variables, member code blocks, etc.). The same type of code, written above load.
(Video tutorial recommendation: java video tutorial)
Example:
public class ExtendsTest { public static void main(String[] args) { // TODO Auto-generated method stub C c = new D(); } } class C { static { System.out.println("C 基类静态域 "); } { System.out.println("C 基类对象成员构造函数"); } public C() { System.out.println("C 基类本身的构造函数"); } } class D extends C { static { System.out.println("D 派生类静态域"); } { System.out.println("D 派生类对象成员构造函数"); } public D() { System.out.println("D 派生类本身的构造函数"); } }
Output result:
The above is the detailed content of When creating a derived class object, what is the execution order of constructors?. For more information, please follow other related articles on the PHP Chinese website!