Skip to content

Instantly share code, notes, and snippets.

@jazlopez
Created July 2, 2023 22:40
Show Gist options
  • Save jazlopez/7e5f80fc11a6491d3cc9ebba778508b1 to your computer and use it in GitHub Desktop.
Save jazlopez/7e5f80fc11a6491d3cc9ebba778508b1 to your computer and use it in GitHub Desktop.
From effective Java 3rd Edition

Enforce noninstantiability with a private constructor

To write a class that is just a grouping of static methods and static fields whose design does not require a constructor to be instantiated.

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

Because the explicit constructor is private, it is inaccessible outside the class. The AssertionError isn’t strictly required, but it provides insurance in case the constructor is accidentally invoked from within the class.

It guarantees the class will never be instantiated under any circumstances.


Jaziel Lopez, Software Engineer, TJ Area, BC. MX

jlopez.mx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment