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

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -