Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the preferred Throwable to use in a private utility class constructor?

Effective Java (Second Edition), Item 4, discusses using private constructors to enforce noninstantiability. Here's the code sample from the book:

public final class UtilityClass {     private UtilityClass() {         throw new AssertionError();     } } 

However, AssertionError doesn't seem like the right thing to throw. Nothing is being "asserted", which is how the API defines the use of AssertionError.

Is there a different Throwable that's typically in this situation? Does one usually just throw a general Exception with a message? Or is it common to write a custom Exception for this?

It's pretty trivial, but more than anything I guess I'm just curious about it from a style and standards perspective.

like image 367
Rob Hruska Avatar asked Dec 29 '08 22:12

Rob Hruska


People also ask

Can we use throws keyword with private constructor?

Yes, constructors are allowed to throw an exception in Java. A Constructor is a special type of a method that is used to initialize the object and it is used to create an object of a class using the new keyword, where an object is also known as an Instance of a class.

What would you use a private constructor?

Private constructors are used to prevent creating instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class.

What is the use case of a private constructor pick one option?

A private constructor in Java is used in restricting object creation. It is a special instance constructor used in static member-only classes. If a constructor is declared as private, then its objects are only accessible from within the declared class. You cannot access its objects from outside the constructor class.

What is the use of private constructor in abstract class?

A private constructor in an abstract class can also serve the purpose of sealed classes (like in Scala or Kotlin etc.). Since you can still provide subclasses from within the abstract class, but outsiders cannot extend/implement (as @Marko Topolnik answered).


2 Answers

There is an assertion: "I'm asserting that this constructor will never be called". So, indeed, AssertionError is correct here.

like image 83
Chris Jester-Young Avatar answered Sep 18 '22 10:09

Chris Jester-Young


I like including Bloch's comment:

// Suppress default constructor for noninstantiability 

Or better yet putting it in the Error:

private UtilityClass() {     throw new AssertionError("Suppress default constructor for noninstantiability"); } 
like image 35
Craig P. Motlin Avatar answered Sep 21 '22 10:09

Craig P. Motlin