Initialization order in Java (static member, static initialization block, normal member, normal initialization block, constructor)

Source: Internet
Author: User

This article links http://blog.csdn.net/xiaodongrush/article/details/29170099

References Article http://my.oschina.net/leoson/blog/103251

1. The order of initialization in a class

(static variable, static initialization block) = = (variable, initialization block, constructor).

2. Two initialization order with an inheritance relationship class

The parent class (static variable, static initialization block) is the subclass (static variable, static initialization block) and the parent class (variables, initialization blocks, constructors) and subclasses (variables, initialization blocks, constructors).
The following examples illustrate:

Class A {public    a () {        System.out.println ("Constructor a");    }    {        System.out.println ("Field A");    }    static {        System.out.println ("Static A");}    } public Class B extends A {public    B () {        System.out.println ("Constructor B");    }    {        System.out.println ("Field B");    }    static {        System.out.println ("Static B");    }    public static void Main (string[] args) {        new A ();        New B ();    }}
Results of new A ()

Static A
Static B
Field A
Constructor A

As a result of new B (), static members and static initialization blocks will only run once.

Field A
Constructor A
Field B
Constructor B

Initialization order in Java (static member, static initialization block, normal member, normal initialization block, constructor)

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.