Thursday, December 22, 2011

Creating Java Object -- Part-IV


The Creating of java object continues….


Enforce nonistantiablity with private constructor

Some special classes needs not be instantiated.  For e.g some utility classes like java.util.Arrays, java.util.Collections is not meant for utility methods rather than creating objects.  In order to force noninstantiablity for such classes we can have a private constructor which does nothing or may be just throwing some error.

public class NonInitializingClass {

    public NonInitializingClass() {
        throw new AssertionError();
    }
}
This will guarantee that no instance of this class will be generated.


{Courtesy: Effective Java - Joshua Bloch} 

No comments:

Post a Comment