Execution sequence of the parent class and subclass constructor in Java

Source: Internet
Author: User

Every time a subclass object is created with the New Keyword, the program will first execute the constructor without parameters in the parent class, and then execute the constructor of the subclass.
Every time a subclass object is created with the New Keyword, the program will first execute the constructor without parameters in the parent class, and then execute the constructor of the subclass.

Eg: I have created three classes: A parent class (a_constructor), a subclass (B _constructor), and a test class (test_constructor ). the code and running result are as follows:

Parent class:

Public class a_constructor {

Public a_constructor (){
System. Out. println ("the non-parametric Constructor ()" of the parent class ()");
}
Public a_constructor (int n ){
System. Out. println ("parent class constructor with parameters (n):" + n );
}
}

Subclass:

Public class B _constructor extends a_constructor {
Public B _constructor (){
System. Out. println ("subclass's non-parameter Constructor ()");
}
Public B _constructor (INT N ){
System. Out. println ("subclass Constructor (n) with parameters:" + n );
}}

Test class:

Public class test_constructor {

Public static void main (string ARGs []) {
B _constructor one = new B _constructor (); // without Parameters
B _constructor two = new B _constructor (2); // with Parameters
System. Out. println ("test ended ");
}
}

Running result:

The parameter-free Constructor () of the parent class ()
The non-parameter Constructor () of the subclass ()
The parameter-free Constructor () of the parent class ()
Subclass Constructor (n) with parameters: 2
Test ended
 
This article from: Development Institute http://edu.codepub.com Source: http://edu.codepub.com/2010/0108/19524.php

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.