Java static block, constructor method load order

Source: Internet
Author: User

Package cn.lay.Test;

/**
* Created by lay on 2017/12/30.
*/
public class Test {
public static void Main (string[] args) {
New C ();
}
}


Class a{
static {
System.out.println ("A static");
}

{
System.out.println ("A");
}

Public A () {
System.out.println ("A constructor");
}
}

Class B extends a{
static {
System.out.println ("B static");
}

{
System.out.println ("B");
}

Public B () {
System.out.println ("B constructor");
}
}

Class C extends b{
static {
System.out.println ("C static");
}

{
System.out.println ("C");
}

Public C () {
System.out.println ("C constructor");
}
}

C inherits from the B,b inherits from the A;ABC respectively has the static domain and the construction method, executes the main method result as follows:

A Static
B Static
C Static
A
A Constructor
B
B Constructor
C
C Constructor

We see that the ABC static domain is loaded in the order of inheritance, and then the non-static is loaded according to the Order of inheritance;

Thus, the loading order is actually determined by the life cycle and the order of dependence;

1, first static domain load, post-construction method loading;

2. Load the parent class first, then load the subclass;

3, the construction method is the latest;

Why can't I load subclasses first?

Because the subclass inherits the parent class, assuming that the child class needs to use the parent class's variable or method, the parent class is not instantiated at this time, then the program will error;

Why can't I load the construction method first?

Simply put, if a static variable is used by a non-static method, then the static field is not executed, and the value of the static variable is wrong.

Java static block, constructor method load order

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.