【Effective Java】条4:通过私有构造器强化不可实例化

在日常开发中,我们经常会写些工具类(虽然名声不是很好)。为了防止调用者不明白进行了实例化调用,我们可以在工具类中添加私有的构造函数。

public class UtilityClass {
    // Suppress default constructor for noninstantiability
    private UtilityClass() {
    }
    ... // Remainder omitted
}

不知大家在平时开发中有没有使用SonarLint进行代码检测。针对工具类,其会提出:

Add a private constructor to hide the implicit public one

修改就是在工具类中添加上私有的构造器即可。

猜你喜欢

转载自blog.csdn.net/xl890727/article/details/80195288