【问题标题】:What does a private constructor do? [duplicate]私有构造函数有什么作用? [复制]
【发布时间】:2016-10-13 08:51:36
【问题描述】:

我正在查看 IntegerCache 类,但它有一个我无法理解的用法。最后一行有一个private 构造函数,但我不明白目的。它有什么作用?

private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer cache[];

    static {
        // high value may be configured by property
        int h = 127;
        String integerCacheHighPropValue =
        sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            try {
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
            } catch( NumberFormatException nfe) {
                // If the property cannot be parsed into an int, ignore it.
            }
        }
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);

        // range [-128, 127] must be interned (JLS7 5.1.7)
        assert IntegerCache.high >= 127;
    }

    private IntegerCache() {}
 }

【问题讨论】:

    标签: java integer


    【解决方案1】:

    这是一个空的构造函数,也是private,防止类的实例化。该类仅用于其静态属性,不能创建该类的实例。

    【讨论】:

    • 我明白了,谢谢~
    【解决方案2】:

    默认情况下,如果没有提供构造函数,Java 编译器将插入一个空的 public 构造函数。通过显式添加一个空的private 构造函数

    private IntegerCache() {}
    

    编译器不会添加默认构造函数。另请参阅JLS-8.8.9. Default Constructor JLS-8.8.10. Preventing Instantiation of a Class (部分)

    通过声明至少一个构造函数、防止创建默认构造函数以及将所有构造函数声明为private,可以将一个类设计为防止类声明之外的代码创建该类的实例。

    public 类同样可以通过声明至少一个构造函数来防止在其包之外创建实例,以防止创建具有public 访问权限的默认构造函数,并通过声明不公开的构造函数。

    【讨论】:

    • 我明白了,谢谢~
    猜你喜欢
    • 2015-11-02
    • 2013-01-20
    • 2019-10-16
    • 2015-10-07
    • 2013-06-24
    相关资源
    最近更新 更多