Item4 Enforce noninstantiability with a private constructor

Sometimes we want to write a class that is just a group of static methods and fields. They can be used --

  1. group related methods on primitive values and arrays (e.g. java.lang.Math or java.util.Arrays)
  2. group static methods, including factories, for objects that implement same interfaces (e.g. java.util.Collections)
  3. group methods on final class, since we cannot put them in subclass.

Theses classes are not designed to be instantiated, so we can add a private constructor for them.

// Nonintantiable Utility class
public class UtilityClass {
  // Suppress default constructor for noninstantiability
  private UtilityClass() {
    throw new AssertionError();
  }
}

As a side effect, the idiom also prevents the class from being subclassed. Because all constructor must invoke its superclass constructor.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home...
    光剑书架上的书阅读 3,977评论 2 8
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,805评论 18 399
  • 这关于蚊子。 每天傍晚去操场锻炼,总有惹人的蚊子来热闹,比起活人,更有活力,也更热衷于似于寄生一类的活动。以前觉得...
    吴说创业阅读 211评论 0 0
  • 早睡早起321天100篇时间管理系统文章第9篇 文章思维导图 古希腊哲人苏格拉底经常问别人一个问题:你是谁? 我时...
    系统思维自我管理训练营阅读 8,875评论 44 473
  • 有一句话说得好,你的心有多宽,你的舞台就有多大;你的格局有多大,你的心就能有多宽。 放大你的格局,你的人生将不可思...
    莫欺少年穷_e70c阅读 137评论 0 0