通过私有构造器强化不可实例化的能力
比如下面的Math类,它只包含静态域和静态方法,这个类的用法就是直接就是用类名点调用方法。这种类大部分是作为工具类来使用,所以实例化这种类是没有任何意义的,为了防止这种类被实例化,通过设置它们的构造器为私有来阻住他们实例化。并且这种类是不能有子类的。因为所有的子类都显式或者隐式的调用了超类的构造器。
package java.lang;
import java.math.BigDecimal;
import java.util.Random;
import jdk.internal.math.FloatConsts;
import jdk.internal.math.DoubleConsts;
import jdk.internal.HotSpotIntrinsicCandidate;
public final class Math {
/**
* Don't let anyone instantiate this class.
*/
private Math() {}
public static final double E = 2.7182818284590452354;
public static final double PI = 3.14159265358979323846;
private static final double DEGREES_TO_RADIANS = 0.017453292519943295;
private static final double RADIANS_TO_DEGREES = 57.29577951308232;
@HotSpotIntrinsicCandidate
public static double sin(double a) {
return StrictMath.sin(a); // default impl. delegates to StrictMath
}
@HotSpotIntrinsicCandidate
public static double cos(double a) {
return StrictMath.cos(a); // default impl. delegates to StrictMath
}
@HotSpotIntrinsicCandidate
public static double tan(double a) {
return StrictMath.tan(a); // default impl. delegates to StrictMath
}
public static double asin(double a) {
return StrictMath.asin(a); // default impl. delegates to StrictMath
}
public static double acos(double a) {
return StrictMath.acos(a); // default impl. delegates to StrictMath
}
public static double atan(double a) {
return StrictMath.atan(a); // default impl. delegates to StrictMath
}
public static double toRadians(double angdeg) {
return angdeg * DEGREES_TO_RADIANS;
}
public static double toDegrees(double angrad) {
return angrad * RADIANS_TO_DEGREES;
}
@HotSpotIntrinsicCandidate
public static double exp(double a) {
return StrictMath.exp(a); // default impl. delegates to StrictMath
}
@HotSpotIntrinsicCandidate
public static double log(double a) {
return StrictMath.log(a); // default impl. delegates to StrictMath
}
........
}