The order in which members are executed when the Java class is created

Source: Internet
Author: User

Static code blocks are executed once when the class is first used, and before the constructor executes. Whenever a class is used, even a new object (such as declaring a variable only) is executed and executed only once. Typically used to initialize a class.

Static code blocks are executed first, and static members (who are executed first). No matter how many new static blocks and static members are executed only once

Then execute the member variable, the last constructor. New member variables and constructors execute several times.

Code:

1. Declaring the Staitcblock class

 Public classStaticBlock1 {Private StaticString tag= "333"; //member Variables    Private  intage1=Setage (); //constructor Function     PublicStaticBlock1 () {LOG.E (TAG,"Constructors"); }    //Static code block    Static{log.e (TAG,"Static code block" ); }    //Static Members    Private Static intAge2=SetAge2 ();  Public Static voidMain (string[] args) {StaticBlock1 B1=NewStaticBlock1 (); StaticBlock1 B2=NewStaticBlock1 (); }    Private intSetage () {LOG.E (TAG,"GetAge1: Method 1" ); return3; }    Private Static intSetAge2 () {LOG.E (TAG,"GetAge2: Method 2" ); return333; }}

2. Create the Staticboloc class in activity

LOG.E (TAG, "OnCreate:------------------------start" );        StaticBlock1 B1=new  StaticBlock1 ();        " ----------------------------------------------------------------------------------" );        StaticBlock1 b2=new StaticBlock1 ();

3. Results

The order in which members are executed when the Java class is created

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.