Java Private constructor: a constructor declared with the Private keyword. Because the constructor of a class is private, this class cannot be instantiated and cannot be inherited . Effective Java Third article: Hardening the Singleton property with a private constructor or enumeration. The so-called Singleton attribute refers to a class that is instantiated only once. Fourth: The ability to harden non-instancing through a private constructor. There are two ways of implementing Singleton in Java:
public class Elvis {public static final Elvis INSTANCE = new Elvis ();p rivate Elvis () {}}public class Elvis {private static Final Elvis INSTANCE = new Elvis ();p rivate Elvis () {}public static Elvis getinstance () {return INSTANCE;}}
Method One: The private constructor can only be called once, To instantiate the public static final domain elvis.instance, once the Elvis is instantiated, there will only be one Elvis instance (the privileged client can invoke the private constructor with the Accessibleobject.setaccessible method through the reflection mechanism);
Method Two: Use static method getinstance to return a reference to the same object, never create another evlis instance;
Why do I need a private constructor if the class cannot be instantiated how to use this class method?
The existence of a private constructor can make certain classes impossible to instantiate and subclass , and these classes are typically tools classes, such as Java.lang.Math, to access the methods of these classes we can define a public static method to implement, such as A.methon ()
public Class A { private A () {} public static void Methon () {} }
The use of private constructors in Java.lang.Math, you can see that the math class is defined as final, using the private constructor, its methods are static, so call its methods only need to Math.sin (x) can:
Public final class Math { private Math () {} public static final double E = 2.7182818284590452354; public static final Double PI = 3.14159265358979323846; public static double sin (double A) { return Strictmath.sin (a),//default impl. Delegates to Strictmath } Publ IC static double cos (double a) { return Strictmath.cos (a);//default impl. Delegates to Strictmath } public s Tatic Double tan (double A) { return Strictmath.tan (a);//default impl. Delegates to Strictmath } ...
public Static float scalb (float f, int scalefactor) { return sun.misc.FpUtils.scalb (f, scalefactor);} }
Java Private Builder