Java Foundation: the execution process of constructing method under the condition of inheritance

Example:

public class BaseParent {
	
	private String name;
	private int age;
	
	public BaseParent() {
		System.out.println("BaseParent : Non parametric structure.....");
	}
	
	public BaseParent(String name, int age) {
		this.name = name;
		this.age = age;
		System.out.println("BaseParent : Parametric structure.....");
	}
	
	public String getName() {
		return name;
	}
	
	public int getAge() {
		return age;
	}
}
public class Parent extends BaseParent {
	
	private String addr;
	
	public Parent() {
		System.out.println("Parent : Non parametric structure.....");
	}
	
	public Parent(String addr) {
		this.addr = addr;
		System.out.println("Parent : Parametric structure.....");
	}
	
	public String getAddr() {
		return addr;
	}
}
public class Child extends Parent {
	
	private String school;
	
	public Child() {
		System.out.println("Child : Non parametric structure.....");
	}
	
	public Child(String school, String addr) {
		this.school =school;
		System.out.println("Child : Parametric structure.....");
	}
	
	public String getSchool() {
		return school;
	}
}

 

Slightly modified:

public class Child extends Parent {
	
	private String school;
	
	public Child() {
		System.out.println("Child : Non parametric structure.....");
	}
	
	public Child(String school, String addr) {
		super(addr);
		this.school =school;
		System.out.println("Child : Parametric structure.....");
	}
	
	public String getSchool() {
		return school;
	}
}

To sum up: if there is a multi-level inheritance relationship, when creating a subclass object, the execution order of the constructor is: from top to bottom, that is, from the highest level of the parent constructor to the current subclass.

If the construction method of the subclass does not explicitly call the parametric construction method of the parent class through super, the system will call the nonparametric construction method of the parent class first by default. In this case, the effect is the same if the "super();" statement is not written.
 
If the construction method of the parent class is explicitly called by super in the construction method of the child class, the corresponding construction method of the parent class will be executed instead of the non parameter construction method of the parent class.

Tags: Programming

Posted on Fri, 10 Jan 2020 11:07:26 -0500 by eduard