as per knowledge singleton design pattern means can create 1 single object of class.
the following code running without error/exception.
i expect code fail because singletonexample
class has private default constructor.
public class singletonexample { private static singletonexample singletoninstance; private singletonexample() { } public static singletonexample getsingletoninstance() { if (null == singletoninstance) { system.out.println("creating new instance"); singletoninstance = new singletonexample(); } return singletoninstance; } public void printsingleton(){ system.out.println("inside print singleton"); } public static void main(string a[]) { singletonexample singobj1 = new singletonexample(); singletonexample singobj2 = new singletonexample(); } }
is there wrong code?
because main
method in class singletonexample
, main
code can access private constructor.
try moving main
method class.
Comments
Post a Comment