Thursday, June 26, 2008

Private Constructors

Prevent your generic 'Utils' classes from being instantiated:
/**
* Template for a Utils class full of Static methods.
* Declare the class as Final so it cannot be subclassed.
*/
public final class MyUtils {

/**
* Provide a Private constructor to prevent instantiation.
*
* Use Assertions (if enabled) or throw an Error in case of
* an attempt is made to instantiate within the class itself.
*/
private MyUtils() {
assert false;
// OR
throw new AssertionError();
}

}

No comments: