Learning object Initialization order _java through Java bytecode analysis

Source: Internet
Author: User

Copy Code code as follows:

Mockery.checking (new Expectations () {

One (new Object ()). ToString ();
Would (ReturnValue (""));

Here's an example of writing a simple class demo

Copy Code code as follows:

public class Test {

int i = 1;
int j = 1;
System.out.println (j);

Public Test () {
i = 2;



Previously used static{} code quickly, you can directly write {} code block

By analyzing Java bytecode, you find that the code is executed in the following order:

1 First executes the constructor method of the object, creates an empty object, and then assigns the default value to the object's field I. Which is to execute i = 0 first (this one should be atomic)

2 then the field is assigned, in our case, there is only one field I, so execute i = 1, this is the field initialization process

4 the {} statement block of the class is executed after the initialization of the field, and if there are more than one {} statement block, executed sequentially in the order of the Code

3 {} The execution of the constructor method i = 2 after execution of the statement is completed

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.