Java static variables, member variables, static code blocks, building blocks loading order __ daily problems

Source: Internet
Author: User

The problem arises from the link below (http://bbs.csdn.net/topics/391908395)

public class statictest{public
    static void Main (String args[]) {
        staticfunction ();
    }
    static Statictest st = new Statictest ();
    static{
        System.out.println ("1");
    }
    Statictest () {
        System.out.println ("3");
        System.out.println ("a=" +a+ "b=" +b);
    }
    public static void Staticfunction () {
        System.out.println ("4");
    }
    {
        System.out.println ("2");
    }
    int a=100;
    static int b=112;
}

Let's take a look at the initialization order of each variable at the time the class loads:
1, initialize the static variables of the parent class, static code blocks, and the order of initialization in the order in which they occur.
2, initialize the static variables of subclasses, static code blocks.
3, initializes the member variable of the parent class.
4, the constructor that executes the parent class.
5, initializes the member variable of the subclass.
6, the construction code block is executed when the object is created.
7, the constructor that executes the subclass. The
results are:
2
3
a=100,b=0
1
4
The key to the cause of this result is in this sentence:
static Statictest st = new Statictest (); A reference to an
St variable is an instance of this class, so the instance is initialized to static initialization when the ST variable is instantiated. Because this sentence is placed at the beginning of the static initialization, the static int b=112 is not invoked, the output is b=0, and the output 1 is also behind 2 and 3. When an object is initialized, the environment variable is initialized first, and then the constructor is executed, and the value of a is 100.

Related Article

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.