Occasionally we want to write a utility class that is just a grouping of static methods and static fields. An
instance would be nonsensical for such classes because these utility classes were not designed to be
instantiated.
Important Points to Remember
Class should have a private constructor
- In the absence of explicit constructors, the compiler provides a public, parameterless default constructor. To a user, this constructor is indistinguishable from any other.
- Classes with public constructor have acquired a bad reputation because some people abuse them to avoid thinking in terms of objects instead of utility classes, but they do have valid uses.
- Class with private constructor make sure that class is noninstantiable by any mean.
Making class Abstract
Making a utility class abstract does not work either because the class can be sub-classed and the subclass instantiated.Example
Source: Effective Java by Joshua Bloch
Post a Comment
Post a Comment