June 2018
Beginner
722 pages
18h 47m
English
As in the case of collections too, a static block can be used to initialize an array static property when some code has to be executed:
class ManageArrays {private static A[] AS_STATIC; static { AS_STATIC = new A[2]; for(int i = 0; i< AS_STATIC.length; i++){ AS_STATIC[i] = new A(); } AS_STATIC[0] = new A(); AS_STATIC[1] = new A(); } //... the rest of class code goes here}
The code in the static block is executed every time a class is loaded, even before the constructor is called. But if the field is not static, the same initialization code can be placed in the constructor:
class ManageArrays { private A[] as; public ManageArrays(){ as = new A[2]; for(int i = 0; i< as.length; i++){ as[i] = new A(); } as[0] =
Read now
Unlock full access