java - Object initialization failed in static block -
i want create array of class objects , initialize without using method wrote code this:
package test; public class test2 { private test2() { } static test2[] arr = new test2[10]; static { (test2 ob : arr) { ob = new test2(); } (test2 ob : arr) { system.out.println(ob); } } public static void main(string args[]) { } }
but when run program, o/p:
null null null null ....
why happening? seems constructor not called when create new object
for (test2 ob : arr) {
gives copy of reference each element in arr
. when write ob = new test2();
you're changing ob
referring to. doesn't change what's in original array.
you need write code arr[n] = new test2();
instead.
Comments
Post a Comment