[Effective Java] Item 4 – Enforce noninstantiability with a private constructor

Published by

on

Summary

  • Utility classes which are made of static methods and static fields are not designed to be instantiated.
  • Without explicit constructors, the compiler automatically creates a default constructor, which means it creates a public constructor with no parameter. Regardless of its intention, this leaves the class to be instantiable.
  • To block from instantiating a class like utility class, we can use a private constructor.
// Noninstantiable utility class
public class UtilityClass {
    // Suppress default constructor for instantiability
    private UtilityClass () {
        throw new AssertionError();
    }
}

Check List

As a side effect, this idiom also prevents the class from being subclassed. All
constructors must invoke a superclass constructor, explicitly or implicitly, and a
subclass would have no accessible superclass constructor to invoke.

  • As the compiler would create a default constructor if not specified, the subclass that doesn’t have any constructor declared will try to call the superclass default constructor by super(). However, as the default constructor of superclass is defined as private, this means the subclass cannot inherit superclass.
  • The compiler also inserts super() at the first line of any constructor to call the superclass default constructor.

Reference

Leave a comment