Java class inheritance constructor order dependency

When Java inherits a class and creates a subclass object, the execution sequence is as follows:

1. Allocate memory for all fields of the subclass and initialize default values ​​(including those inherited from the parent class), and then execute the constructor (if not defined, execute the default no-argument constructor)

2. Each constructor execution will go through three stages (note that this is a recursive process):

    2.1 Explicitly call (super) the constructor of the parent class or implicitly call the no-argument constructor of the parent class. If the this constructor is explicitly called, the call chain will be executed until an explicit or implicit parent class constructor call is encountered

    2.2 Initialize fields using initializers or any initialization block

    2.3 Executing the constructor body

Let's see an example:

A.java:

package study;


public class A {
	A()
	{
		System.out.println("A()");
		this.testpublic();
		this.testprivate();
	}
	A(int i)
	{
		System.out.println("A("+i+")");
		testpublic();
	}
	public void testpublic()
	{
		System.out.println("A.testpublic()");
	}
	private void testprivate()
	{
		System.out.println("A.testprivate()");
	}
}

B.java

package study;


public class B extends A {
	B(){
		this(4);
		System.out.println("B()");
	}
	B(int i)
	{
		System.out.println("B("+i+")");
	}
	public void testpublic()
	{
		System.out.println("B.testpublic()");
	}
	public void testprivate()
	{
		System.out.println("B.testprivate()");
	}
}

Main.java

package study;

public class Main {
	public static void main(String argv[])
	{
		A b = new B();
		b.testpublic();
	}
}

You can first think about what the running result will be. Here is the program running result:


B()->B(4)->A()->B(4)->B()

We can see that this is a recursive process. In fact, the execution phase of A() is ignored here. A is inherited from the Object class by default. That is to say, the constructor of A will continue to call the parent class recursively. Object's constructor, up to the top-level class.

We also saw the nature of Java polymorphism at the constructor level. Pay attention to the difference between public and private here. As for the specific reasons, I haven't clarified yet. If anyone knows, I hope to give pointers!


Guess you like

Origin blog.csdn.net/g1093896295/article/details/79984698