singleton - What are the advantages and disadvantages of creating an Object in static block in Java? -


this question might blunder of java experts. know why create objects in static method main not in static block. understand going create object unnecessarily if instantiate in static block , of course if don't use further. there other things noted approach ? can relate singleton pattern ?

for example:

public class myclass {      static {         anotherclass object = new anotherclass();             // operations here object.     } } 

the main reason control on when gets executed. stuff in static block executed first time class loaded , it's easy accidentally cause class loaded (for instance referencing constant on class).

having static method means have complete control on when method called (because have explicitly call it).

in regards singletons, java idiom eagerly loaded singletons initializes instance static field. run same static block.

public class singleton {     private static final singleton instance = new singleton();      private singleton() {}      public static singleton getinstance() {         return instance;     } } 

Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -