Home > Java > Javagetting Started > When creating a derived class object, what is the execution order of constructors?

When creating a derived class object, what is the execution order of constructors?

王林
Release: 2020-07-08 15:55:21
Original
9705 people have browsed it

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, 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.

(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 派生类本身的构造函数");
	}
}
Copy after login

Output result:

When creating a derived class object, what is the execution order of constructors?

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template