classstaticcode{intAge ; //Static code block Static{System.out.print ("Static"); } //Building Code Blocks{System.out.print ("55"); } //constructor FunctionStaticcode (intAge ) { This. age=Age ; System.out.print ( Age+","); } voidShow () {//Local code block { intAge=30; } System.out.print ("Show:" +age+ ","); }}classstaticcodedemo{ Public Static voidMain (string[] args) {staticcode P1=NewStaticcode (20); P1.show (); Staticcode P2=NewStaticcode (20); }}
Execution Result: static,55,20,show,55,20
Analysis:
1, first execute Staticcode this class, so static
2. Create P1 object, execute construct code block, 55
3. Perform constructor initialization, 20
4, Executive P1.show (), show:20
5. Create P2 object, execute construct code block, 55
6. Perform constructor initialization, 20
Summary: The static code block is loaded only once, as the class is loaded. The function is to initialize the class.
Constructs a block of code that can be initialized for all objects. The creation of several objects is called several times, which is the initialization of generality for the object.
A constructor is a targeted initialization of a corresponding object.
A local code block defines the life cycle of a variable in a function, age=30 the local code executes. It's automatically released.
Differences between building blocks of code, static code blocks, and local code blocks in Java