Wednesday, September 23, 2015

Effective Java - Item 4 : Enforce noninstantiability with a privateconstructor

There are occasions when we would want to use some common methods without worrying about instantiating the class it is contained in. For example we would want to use math functions like log, sin, cos etc. All these are grouped together in a utility class java.lang.Math and all the methods are made static. Now we need to note that these are just utility classes and it does not make sense to instantiate them. However all classes have a default public constructor.

Making the class abstract does not ensure that it should not be instantiated since it can be subclassed and the subclass instantiated. So a good solution is to provide a private constructor. This also ensures that the class cannot be subclassed and instantiated. Because the explicit constructor is private, it is inaccessible outside of the class.

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

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

No comments:

Post a Comment