Initialization Order of Java classes (static variables, static initialization blocks, variables, initial ...

Source: Internet
Author: User

It's an interesting article.

1. No inheritance

Static variable, static initialization block, variable initialization block----construction method

2. There are cases of succession

Parent static variable, parent static initialization block, subclass static variable, subclass static variable initialization block, parent class variable initialization, parent class variable initialization block, child class variable initializer--subclass variable initialization block-- > Sub-Class construction methods

--------------------------------------------------I am the copy split line---------------------------------------------------------

When you go to the interview, you often encounter such questions: give you two classes of code, they are inherited relationships, each class only the constructor method and some variables, the constructor may have a piece of code on the value of the variable to do some of the operation, there are some of the variable value output to the console of the Code, Then let's judge the result of the output. This is actually a look at our understanding of the initialization order of classes in the case of inheritance.

As we all know, for static variables, static initialization blocks, variables, initialization blocks, constructors, they are initialized in order (static variables, static initialization blocks) > (variables, initialization blocks) > constructors. We can also verify this with the following test code:
Java code
public class Initialordertest {

static variables
public static String Staticfield = "static variable";
Variable
Public String field = "Variable";

Static initialization blocks
static {
System.out.println (Staticfield);
SYSTEM.OUT.PRINTLN ("Static initialization Block");
}

Initialize block
{
System.out.println (field);
System.out.println ("initialization block");
}

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

public static void Main (string[] args) {
New Initialordertest ();
}
}

Running the above code, we will get the following output result:

static variables
Static initialization blocks
Variable
Initialize block
Constructors

This is in full conformity with the above mentioned. So what happens to the inheritance? We still get the final result with a test code:
Java code
Class Parent {
static variables
public static String P_staticfield = "Parent class-static variable";
Variable
Public String P_field = "Parent class-variable";

Static initialization blocks
static {
System.out.println (P_staticfield);
System.out.println ("Parent class-static initialization block");
}

Initialize block
{
System.out.println (P_field);
System.out.println ("Parent class-Initialization block");
}

Constructors
Public Parent () {
System.out.println ("Parent class-constructor");
}
}

public class Subclass extends Parent {
static variables
public static String S_staticfield = "sub-class-Static variable";
Variable
Public String S_field = "Subclass--variable";
Static initialization blocks
static {
System.out.println (S_staticfield);
System.out.println ("Subclass-static initialization block");
}
Initialize block
{
System.out.println (S_field);
System.out.println ("Subclass-Initialization block");
}

Constructors
Public Subclass () {
System.out.println ("Subclass--constructor");
}

Program entry
public static void Main (string[] args) {
New Subclass ();
}
}

Run the above code, and the results will immediately appear in front of us:

Parent class--Static variable
Parent class--static initialization block
Subclass--Static variables
Subclass--Static initialization block
Parent class--variable
Parent class--initialization block
Parent class--constructor
Subclass--Variables
Subclass--Initialization block
Sub-class--constructor

Now, the results have been self-evident. One might notice that the initialization of subclasses is not done until the parent class is fully initialized, and that the initialization of the static and static initialization blocks of the subclass is done before the variables of the parent class, initialization blocks, and constructors are initialized.

What about the sequence between static and static initialization blocks, variables, and initialization blocks? Is the static variable always initialized before the static initialization block, and the variable always initializes before the initialization block? In fact, it depends on the order in which they appear in the class. We describe static variables and static initialization blocks as examples.

Again, let's write a class to test:
Java code
public class Testorder {
static variables
public static TestA a = new TestA ();

Static initialization blocks
static {
SYSTEM.OUT.PRINTLN ("Static initialization Block");
}

static variables
public static Testb B = new Testb ();

public static void Main (string[] args) {
New Testorder ();
}
}

Class TestA {
Public TestA () {
System.out.println ("Test--a");
}
}

Class Testb {
Public Testb () {
System.out.println ("Test--b");
}
}

Running the above code, you will get the following result:

Test--a
Static initialization blocks
Test--b

You can change the position of the variable A, variable B, and the static initialization block at will, and you'll see that the output changes as they appear in the class, which means that static variables and static initialization blocks are initialized in the order they are defined in the class. Similarly, variables and initialization blocks follow this pattern.

After understanding the initialization order of the classes under inheritance, how to determine the final output is solved.

The initialization of static blocks and static members is independent of the instantiation process, which must first execute static blocks and static members, but does not mean that the instantiation will necessarily execute static and static members. This is done only when the corresponding class of the instantiation is loaded into the virtual machine. Sometimes it is not necessary to instantiate a static block or initialize a static member, such as investigating a static member of the class or a static method, such as a subclass of the class being instantiated or invoking a static member or static method.

and the actual order of instantiation is actually (omitting the class initialization process)
1, enter the current class construction method.
2, into the parent class construction method recursion until the Java.lang.Object class construction method.
3, executes the Java.lang.Object class constructs the method, sequentially is the member variable initial and the initialization block (installs the context order), corresponds to the call construction method body.
4. Execute the constructor of the direct subclass of the Java.lang.Object class, which recursively passes to the current class.
5, the current class execution sequence is the same as the previous Java.lang.Object class.

The nature of the construction method is actually a normal non-return parameter called the <init> method, but the virtual machine calls this method of the instruction is different from other methods, its calling instruction is the same as the instructions to call the private method.
There are three methods of calling instructions in the virtual machine, and these three call commands are different in efficiency.
The invocation of an interface method, which is the slowest call.
The calling instruction of the ordinary class method, which is of medium speed.
Constructs the method with the private method invocation instruction, which is the fastest.

Initialization Order of Java classes (static variables, static initialization blocks, variables, initial ...

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.