公用的工具类不应该有公共的构造函数

Sonarlint检测出如下问题:

Utility classes should not have public constructors

  Utility classes, which are collections of static members, are not meant to be instantiated. Even abstract utility classes, which can be extended, should not have public constructors.
  Java adds an implicit public constructor to every class which does not define at least one explicitly. Hence, at least one non-public constructor should be defined.

公用的工具类不应该有公共的构造函数

公用的工具类是静态成员的集合,并不意味着要实例化。甚至扩展的抽象工具程序类也不应该有公共构造函数。

Java会向不定义构造函数的每个类添加隐式的公共构造函数。因此,应该定义至少一个非公共构造函数。

错误代码示例:

class StringUtils { // Noncompliant      
    public static String concatenate(String s1, String s2) {
        return s1 + s2;
    }
}

 

正确代码示例:

class StringUtils { // Compliant    

    private StringUtils() {
        throw new IllegalStateException("Utility class");
    }

    public static String concatenate(String s1, String s2) {
        return s1 + s2;
    }
}

  

例外情况:

当类包含 public static void main(String[] args) 方法时,它不被视为工具类类,并且将被该规则忽略。

    原文作者:贾树丙
    原文地址: https://www.cnblogs.com/acm-bingzi/p/java-private-constructor.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞