The code block is divided into 3 cases. 1, Common code block This is the most common way to write code, and we are most familiar with it, which usually appears in code blocks of methods and statements.
2, building blocks of code Constructs a block of code that is written directly in the class. It is preferable to the construction method execution, and it is worth reminding that the construction code block is run every time the object is instantiated.
3, Static code block The essence is a constructed block of code that is decorated with the static keyword, which executes before the main method, runs before the code block is constructed, and differs from the construction code block, regardless of how many times the object is instantiated are executed only once.
Put a code, let's have a clearer understanding
- Package Reviewdemo;
- /**
- * Test the priority of each code block
- * Priority order: Static code block > Construction code block > common code block
- * Note: No matter how many objects are created, static code blocks are executed only once!
- */
- public class Demo13 {
- Demo13 () {
- System.out.println ("I am the construction Method!") ");
- }
- {
- System.out.println ("I am building blocks of code! ");//Instantiate the object when it is called!
- }
- static{
- System.out.println ("I am a static code block! ");
- }
- public static void Main (string[] args) {
- New Demo13 ();
- New Demo13 ();//Create the object again, proving that the static code block executes only once, no matter how many objects are created
- System.out.println ("I'm an ordinary code block!") ");
- }
- }
Copy Code The result of the operation is: I am a static code block! I'm building blocks of code! I'm the construction method! I'm building blocks of code! I'm the construction method! I am an ordinary code block!
|
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
To talk about code blocks.