Java Static code block and constructor initialization sequence

Source: Internet
Author: User

Java Static code block and constructor initialization sequence

What is the initialization sequence of the Static code block and constructor in Java?
For example, it is also a type of question that is frequently used in pen test questions.

The three classes are ClassA, ClassB, and ClassC. B inherits from A and C from B.

public class ClassA {    static{    System.out.println(init in static A);    }    public ClassA() {    System.out.println(init in ctor A);    }}
public class ClassB extends ClassA{    static{    System.out.println(init in static B);    }    public ClassB() {    System.out.println(init in ctor B);    }}
public class ClassC extends ClassB{    static{    System.out.println(init in static C);    }    public ClassC() {    System.out.println(init in ctor C);    }}

Run it and check the result. Is it consistent with your expectation ???

Init in static
Init in static B
Init in static C
Init in ctor
Init in ctor B
Init in ctor C

Loading sequence:
Class loading-> static code block running-> static variable initialization-> corresponding constructor running

 

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.