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