Item 04 - Enforce noninstantiability with a private constructor

From Effective Java 2/e by Joshua Bloch

Utility classes are not intended to make any constructor

  • private constructor can prevent to create an object
  • Sub-class can't be created
/**
 * DipPixelHelper
 *
 * @author The Finest Artist
 */
public class DipPixelHelper {

   // Suppress default constructor for noninstantiability
   private DipPixelHelper() {
      throw new AssertionError();
   }

   public static float getPixel(Context context, int dip) {
      Resources r = context.getResources();
      return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, r.getDisplayMetrics());
   }

   public static float getPixel(Context context, float dip) {
      Resources r = context.getResources();
      return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, r.getDisplayMetrics());
   }
}

Posted by The Finest Artist