Initialization order in Java [Java]

Source: Internet
Author: User

First look at the program:

1  PackageInit_cls;2 3 classa{4 5{System.out.println ("I am in the class a!");}6     Static{System.out.println ("Static is the class A"));}7 }8  Public classInit_cls {9{System.out.println ("I am in the Init_cls");}Ten     Static{System.out.println ("I am static in the Init_cls class");} One      Public Static voidMain (string[] args) { A         //TODO auto-generated Method Stub -          -A a=NewA (); theInit_cls c=Newinit_cls (); -     } -  -}

The result of the operation is:

I am static in the Init_cls class
Static is the class A
I am in the class A!
I am in the init_cls

As you can see from the results, when we just use a method in a class (the main in the init_cls used here), only the static variable is initialized, so the first output: I am static in the Init_cls class

Then, when instantiating a Class A, the static domain static is initialized, so the output: static is the Class A

After initializing the non-static domain, the output: I am in the class A!

Finally, the non-static domain in Class A is initialized only when we instantiate the Init_cls class, with the output: I am in the init_cls

These are very different from the order of initialization in Python, when a package is loaded in Python, it is initialized from top to bottom, all executed when the statement is encountered

Initialization order in Java [Java]

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.