The initialization process of Java

Source: Internet
Author: User

In the process of brushing a question, you often encounter problems with the initialization order of classes in Java.

Summarized as follows, easy to review later:

Initialization process:

    1. First, static member variables and static code blocks in the parent class are initialized in the order in which they appear in the program;
    2. Then, initialize the static member variables and static code blocks in the subclass, initializing them in the order in which they appear in the program;
    3. Second, initialize the normal member variables and code blocks of the parent class, and then execute the parent class construction method;
    4. Finally, the normal member variables and code blocks of the subclass are initialized, and then the construction methods of subclasses are executed.

Examples are as follows:

classC {C () {System.out.print (C); }} classA {c c=NewC (); A () { This("A"); System.out.print (A);    } A (String s) {System.out.print (s); }} classTestextendsA {Test () {Super("B"); System.out.print (B); }      Public Static voidMain (string[] args) {NewTest (); }}

In the above program, the initialization process of new class test is as follows:

    1. The constructor method is called to initialize the child object, but because test inherits from Class A, you need to call A's construction method first;
    2. In test's construction method, the parameter construction method of the parent class is explicitly called by Super("B") , and no parameter construction method is called.
    3. Before executing A's construction method, it is necessary to initialize its member variables so that the C constructor is executed.
    4. As a result, the final order of invocation is: Class C's parameterless constructs--Class A's parameter constructs--class test constructs the remainder of the method.

So the result of the final output is:

CBB

The initialization process of Java

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.