zoukankan      html  css  js  c++  java
  • 公用的工具类不应该有公共的构造函数

    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) 方法时,它不被视为工具类类,并且将被该规则忽略。

  • 相关阅读:
    网站架构(页面静态化,图片服务器分离,负载均衡)方案全解析
    ant例子
    poj 3744 概率dp+矩阵快速幂
    hdu 4284 状态压缩dp
    hdu 4276 树形dp
    hdu 3586 树形dp+二分
    hdu 3001 三进制状压
    hdu 1561 树形dp+分组背包
    hdu 2196 树形dp
    poj 1485 dp
  • 原文地址:https://www.cnblogs.com/acm-bingzi/p/java-private-constructor.html
Copyright © 2011-2022 走看看