The content of this article:
- Local code block
- Building code Blocks
- Static code block
- Add
Starting Date: 2018-03-28
Local code block:
A local code block is used to limit the life cycle of a variable, and if you want some variables to fail directly after a procedure and you do not want to continue later, you can use local variables to limit the lifetime of a variable to a local code block
To construct a code block:
- The constructor initializes the corresponding object only, and constructs a code block to initialize all objects of the class .
- Because the code block is constructed to initialize all objects of the class , variables that are initialized to the same value for each object can prevent initialization in the construction code block.
classperson{String Gender; intAge ; { //Building Code BlocksSystem.out.println ("Construct code block run phase"); Gender= "Male"; } person () {//constructor FunctionSystem.out.println ("Constructor person () run phase"); } person (intAge) {//constructor FunctionSystem.out.println ("constructor person (int) Run phase")); This. age=Age ; } } Public classDemo { Public Static voidMain (string[] args) {person P1=NewPerson (); System.out.println (P1.gender); Person P2=NewPerson (18); System.out.println (P2.gender); }}
The above code results:
construct code block run phase Constructor person () run phase male construction code block run phase constructor person (int ages) Run phase male
Examples of the benefits of constructing code blocks:
Constructor version:
To construct a code block version:
Static code block:
- Static blocks of code, unlike building blocks of code, are executed only once to initialize the entire class, typically initializing class variables.
- Only class variables can be modified in static code blocks.
- Static code blocks are executed earlier than the main function.
- Sometimes because static code blocks are executed only once. So sometimes it's used to "show the program flow."
classperson{StaticString Gender; intAge ; Static{System.out.println ("Static code block execution Complete"); Gender= "Male";//the changed variable can only be a class variable} person () {//constructor FunctionSystem.out.println ("Constructor person () run phase"); } person (intAge) {//constructor FunctionSystem.out.println ("constructor person (int) Run phase")); This. age=Age ; }} Public classDemo { Public Static voidMain (string[] args) {person P1=NewPerson (); System.out.println (P1.gender); Person P2=NewPerson (18); System.out.println (P2.gender); }}
The above code executes the result:
Static code block execution completion constructor person () run phase male constructor man (int age ) Run phase male
Add:
- Order of operation of each initialization block: Static code block-"construct code block-" Construction method
Java: Building blocks of code, static blocks of code