About JAVA static initialization blocks, initialization blocks, and the calling sequence of Constructors

Source: Internet
Author: User

A simple example of initialization block, static initialization block, and the execution sequence of the constructor is as follows:

The parent class is as follows:

[Java]
Package test. jamin;
/**
* ClassName: Father
*
* @ Author wangjieming
* @ Version 1.0
* @ Since v1.0
* @ Date 2012-7-2 2:13:57 pm
*/
Public class Father {
 
Static {
System. out. println ("Father Static Block ");
}

{
System. out. println ("Father Block ");
}

Public Father (){
System. out. println ("Father Constructor ");
}


}

Subclass:

[Java]
Package test. jamin;
/**
* ClassName: Child
*
* @ Author wangjieming
* @ Version 1.0
* @ Since v1.0
* @ Date 2012-7-2 2:16:42 pm
*/
Public class Child extends Father {
 


Static {
System. out. println ("Child Static Block ");
}

{
System. out. println ("Child Block ");
}

Public Child (){
System. out. println ("Child Constructor ");
}

Public static void main (String [] args ){
Child c = new Child ();
}

}

Analysis:

Subclass inherits the parent class:

First, call the static initialization block of the parent class, and then call the static initialization block of the subclass.

-------------------------------- Split line -----------------------------------

If the child class is instantiated, the parent class initialization block and the parent class constructor are called. Then, the Child class initialization block and the Child class constructor are called.

The running result is as follows:

 
Author: jamin0107

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.