Item 4: Enforce noninstantiability with a private constructor

In the previous post we made a class singleton by enforcing a private constructor and exposing a public static final instance. This item of the book effective java is no different. Here too the author Joshua Bloch suggests-

  1. Making a class abstract will not prevent it from being initialized. The abstract class can always be sub-classed and the subclass can be initialized, thus initializing the parent class.
  2. The only way to ensure non-instantiability of a class is to make the constructor private.

e.g.

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

When will I make my constructor private?

In case you are thinking that when would we want our class to never be instantiated. When do we need a class where we need no instance of that class. Well, such classes can be used as the ….

  1. Utility classes/ Helper classes
  2. They could be a group of static factory methods as discussed in the Item post which talks in detail about static factory methods.
Advertisements

About Gaurav

I'm Gaurav; friends call me Teddy, n i'm shivi fr my family!! A java enthusiast who likes experimenting with what he knows. View all posts by Gaurav

One response to “Item 4: Enforce noninstantiability with a private constructor

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: