java - When to use initializers? -


this question has answer here:

i came across following bit of java syntax:

static { ...  } 

apparently known "static initializer" (see static block in java) , "executed when class loaded". when should static initializer used? advantages , disadvantages compared initializing variables in usual way?

as mentioned in comments , linked posts, useful when static initialization requires logic beyond assigning values static fields, e.g.:

public class mediocreexample {      static list<string> strings = new arraylist<string>();      static {         strings.add("first");         strings.add("second");     }  }         

there alternatives not use initialization block:

public class mediocreexample {      static list<string> strings = createinitiallist();      private static list<string> createinitiallist () {         list<string> = new arraylist<string>();         a.add("first");         a.add("second");         return a;     }  } 

there isn't compelling reason use non-initializer alternative -- can see initializer version clear , succinct -- i'm including illustrate point: don't make design decisions blindly, know why you're choosing option choosing.

sometimes there no convenient alternatives that, e.g. if goal print console on static initialization:

public class mediocreexample {      static {         system.out.println("mediocreexample static init.");      }      } 

there other ways generate equivalent code cleanest.

but usual, use way appropriate , provides clearest , maintainable code. language way express idea, speak (type) clearly.


Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -