JAVA Parent-Child class constructor, static code block, and other execution sequence

Source: Internet
Author: User

JAVA Parent-Child class constructor, static code block, and other execution sequence

 
Recently, I encountered a Java constructor when I was working on the project, and I learned some execution sequence knowledge about code blocks. I just ran an experiment on it. When subclass A inherits the parent class B

A a = new A();

In this case, what is the sequence of the static code blocks and constructor executions of the parent class and subclass?
My conclusion is:
Parent Class B static code block-> subclass A static code block-> parent class B non-static code block-> parent class B constructor-> subclass A non-static code block-> subclass A constructor

See the code below:

Public class Parent {public Parent () {System. out. println (parent constructor method);} static {System. out. println (parent static code);} // non-static code block {System. out. println (parent nonStatic code );}}
Public class Children extends Parent {public Children () {System. out. println (children constructor code);} static {System. out. println (children static code);} // non-static code block {System. out. println (children nonStatic code);} public static void main (String [] args) {Children c = new Children ();}}

Output result:

The code is not difficult. It is particularly noted that the static code block of the subclass in the output result follows the static code block of the parent class. In this case, you should pay special attention to it.

 

Related Article

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.