Java initialization block (static) Order

Source: Internet
Author: User
Public class person {A = 6; // if (a> 4) {system. out. println ("person init Block A> 4") ;}} public int A = 9; {system. out. println ("second executed");} static {// The system is executed even if the object is not instantiated. out. println ("person static block");} public static void main (string [] ARGs) {// person P = new person (); // system. out. println ("A" + P. a); leaf L = new leaf (); leaf LL = new leaf () ;}} class root {static {system. out. println ("root static init");} {system. out. println ("root normal init");} public root () {system. out. println ("root constructor");} class mid extends root {static {system. out. println ("mid static init") ;}{ system. out. println ("mid normal init");} public mid () {system. out. println ("mid constructor") ;}} class leaf extends mid {static {system. out. println ("leaf static init");} {system. out. println ("leaf normal init");} public leaf () {system. out. println ("leaf constructor ");}}

Output result:

Person static Block
Root static init
Mid static init
Leaf static init
Root normal init
Root Constructor
Mid normal init
Mid Constructor
Leaf normal init
Leaf Constructor
Root normal init
Root Constructor
Mid normal init
Mid Constructor
Leaf normal init
Leaf Constructor

Initialization sequence:

Static initialization block (parent class ---> subclass) ----> non-static initialization block of the parent class (declaring the default value of the attribute instance (the execution sequence is determined by the sequence in which the initialization block and default value are declared )) -----> constructor of the parent class -------> non-static initialization block of the subclass (declaring the default value of the attribute instance (the execution sequence is determined by the sequence in which the initialization block and default value are declared )) ---------> constructor of subclass

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.