Java compile-time initialization order

Source: Internet
Author: User

In some cases, the initialization of Java will have a great impact on my work, so simply introduce

The initialization of simple variables is introduced first: within the class, the order in which the variables are defined determines the order in which they are initialized, even if the definition of the variable is scattered between the method definitions, and it is initialized before the constructor and method.

public class test{
public static void Main (string[] args) {
Test2 test2 = new Test2 ();
TEST2.F ();
}
}
Class test1{
Public Test1 (int i) {
System.out.println ("This is Test1" +i);
}
}
Class test2{

Test1 test1;
Test1 test11 = new Test1 (1);
Public Test2 () {
System.out.println ("This is Test2");
System.out.println ("Here is Test1" +test1);
Test1 = new Test1 (1111);
test13 = new Test1 (33);
}
Test1 test12 = new Test1 (2);
public void F () {
System.out.println ("This is f ()");
}
Test1 test13 = new Test1 (3);
}

The output is:

This is Test11
This is Test12
This is Test13
This is Test2
Here is test1 null
This is Test11111
This is Test133
This is F ()

From this you can see that the order of initialization is: Inside the class, the order in which the variables are defined determines the order in which they are initialized, even if the definition of the variable is scattered between the method definitions, and it is initialized before the constructor and method.

Initializes the variable even when the constructor or definition is initialized but there is no way to prevent the default initialization of the system;

If there is a static variable, then the static variable will be initialized first, then the normal variable is initialized, the static variable is initialized only once, and is initialized when the class is first used.

Java compile-time initialization 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.