通过私有构造器强化不可实例化的能力

通过私有构造器强化不可实例化的能力

比如下面的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
    }
........


  
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值