Recently, I found that an array can be initialize as follows:
private static int[] _array = new int[4];
// An arbitrary amount of code
{
_array[0] = 10;
_array[1] = 20;
_array[2] = 30;
_array[3] = 40;
}
What is this form of initialization called? What are its limitations?
This is instance member initialization using an initializer block , and it looks a lot like static initialization which would prefix that block with the word static
.
Its limitations would match that of any constructor as the Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
It is initialization block and regarding to documentation :
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors
I've answered yesterday in similar post here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.