I have a Singleton Logger class.
public class Logger { public static Logger INSTANCE = new Logger(); private Logger() { ... } }
I want my constructor to start a new instance. So my code is as follows:
public class MyClass { public MyClass() { Logger.INSTANCE.log("MyClass created"); ... } }
I am wondering if this could break static instances of MyClass . For example, if I have:
public class MyOtherClass { private static MyClass myClass = new MyClass(); ... }
I am afraid that this might cause a problem due to the undefined order of initialization of static variables. Therefore, if MyClass initialized before Logger.INSTANCE , then the MyClass construction fails. Is there any mechanism to prevent this, or is using static variables in the constructor inherently dangerous? Is there a way to prevent users from creating static instances of MyClass in this case?
source share