In this article, I will use an example to show what is an instance variable initialization block, an instance initialization block and a static initialization block, and then how the instance initialization block works in Java.
Execution order
Look at the code below, do you know which one to execute first?
PackageSimplejava;classFoo {//instance variable initializerString s = "abc"; //Constructor PublicFoo () {System.out.println ("Constructor called"); } //static initializer Static{System.out.println ("Static initializer called"); } //instance initializer{System.out.println ("Instance initializer called"); }} Public classQ27 { Public Static voidMain (string[] args) {NewFoo (); NewFoo (); }}
Result output;
Static initializer called
Instance initializer called
Constructor called
Instance initializer called
Constructor how the called instance Initialization block works
The above instance initialization block contains a print statement. To understand how it works, we can think of it as a variable assignment statement, such as B=0, which is easier to understand.
int b=0, can be written as int b; b=0;
Therefore, the instance initialization block is basically similar to the instance variable initialization block.
When to use instance initialization blocks
Instance initialization blocks are seldom used, but can be substituted as instance variable initialization blocks in the following cases:
- Initialization code needs to handle exceptions;
- Perform calculations that cannot be represented by instance variable initialization blocks;
Of course, the code can also be written in the constructor method, but if a class has more than one constructor, you need to write the code repeatedly in each constructor method.
If you use an instance initialization block, you only need to write it once, and it executes regardless of which constructor method you use to create the class. (I think this is an infrequently used concept.) )
Another case is an anonymous inner class, which is useful because it cannot declare a constructor method. (Is it appropriate to place the log function in this place?) )
Thank Derhein.
An anonymous class that implements an interface does not have a constructor method, so an instance initializes a block alternative to a construction method that executes various expressions during object construction.
Link: http://www.programcreek.com/2011/10/java-class-instance-initializers/
"Simple Java" What is a Java instance initialization block