Call parent class constructor of Java constructor __ block chain

Source: Internet
Author: User

Subclasses can explicitly invoke the constructor of the parent class through the Super keyword.

When the parent class does not provide a parameterless constructor, the constructor of the parent class must be explicitly called in the constructor of the subclass;

If the parent class provides a parameterless constructor, the constructor of the subclass can call the parent class's constructor without explicitly calling the parent class's parameterless constructor by default.

Package com.bjut.StudyTest;

Class Person {public Person
	() {
		System.out.println ("Base has no args.");

	Public person (String temp) {
		System.out.println ("Base:" + temp);
	}
}

Class Student extends Person {public
	Student () {
		super ("a");
		System.out.println ("Student has no args.");
	}

	Public Student (String temp) {
		System.out.println ("Student:" + temp);
	}

public class Testconstruction {public

	static void Main (string[] args) {person
		p = new Student ();//Call the constructor of the parent class first To display the invocation of the specified parent class constructor.
		Student s = new Student ("B");//The constructor of the parent class is called first, and the parent class parameterless constructor is called by default.
	}

}
Output:

Base:a
Student has no args.
Base has no args.
Student:b

When there is a parent class, the constructor of the parent class is executed before the object is instantiated, and then the constructor of the subclass is executed.

(Supplemental) The order in which the Java program initializes the execution of the work:

Parent class static variable-> parent class static code block-> subclass static variable-> subclass static code block

-> Parent class non-static variable-> static code block-> parent class constructor

-> Subclass Non-static code block-> subclass non-static variable-> sub-class constructor


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.