1. Static initialization block
Static initialization blocks are only executed once when the class is first loaded , while static initialization blocks can only assign values to static variables and cannot be assigned to normal member variables.
2. (non-static) initialization block
(non-static) initialization blocks are executed once each time the instance object is generated , and any variable can be assigned a value.
3. Construction method
The construction method executes once each time the instance object is built
4. Execution order: Static initialization block---initialization block----construction method
The test code is as follows:
1 Public classSonextendsFather {2 Static intSnum = 0;3 intnum = 0;4 Public Static voidMain (string[] args) {5SYSTEM.OUT.PRINTLN ("-----");6 NewFather ();7SYSTEM.OUT.PRINTLN ("-----");8 NewSon ();9SYSTEM.OUT.PRINTLN ("-----");TenSystem.out.println ("Snum =" +snum); One } A - PublicSon () { -System.out.println ("Son construction Method"); the } - - Static { - //num = 1; //Error: Cannot assign a value to a non-static variable +Snum = 1; -System.out.println ("Son static initializer"); + } A at { -System.out.println ("Son initialization block"); - } - - } - in classFather { - { toSystem.out.println ("Father initialization Block"); + } - the PublicFather () { *System.out.println ("Father construction Method"); $ }Panax Notoginseng - Static { theSystem.out.println ("Father static initializer"); + } A}
View Code
The test results are as follows:
Summary:
- The static initialization block has the highest precedence, that is, the first execution, and only when the class is loaded for the first time ;
- Non-static initialization blocks and constructors are executed and executed once each time the object is generated ;
- The code for a non-static initial block is executed before the class constructor . Therefore, in order to use, we should develop the habit of writing the initialization block before the constructor, which is easy to debug;
- Static initialization blocks can be used either to initialize static member variables or to execute initialization code ;
- Non-static initialization blocks can be code reused for multiple overloaded constructors.
Executes only once, when the class is first loaded.
Java: Initialization blocks, static initialization blocks, execution order of construction methods