Still Have Public No-arg Constructors in Util Classes?

If your answer is "No", check again. Even if there is no public no-arg constructor physically in the java file, the compiler will generate one in the class file, the default constructor. You can disable this by adding a private no-arg constructor. This is what I would recommend in every new utility class:
private Util() {
//disable external instantiation
}
By utility class, or helper class, I mean those classes having only static methods and fields, whether they are public or protected. They are much like a kitchen sink. They don't represent any entities in your model, and have no distinct identity. Therefore, they should never be instantiated. By disallowing instantiation, you also save a little memory usage.

These "handy classes full of static functions" are developers' favorite, used in every project. Can you name a project without a utility class? Unfortunately, a lot of them still implicitly allow instantiation. For instance, these classes in JDK:
  • java.util.XMLUtils (package-level class, not public, but still doesn't make sense to allow itself to be instantiated)

  • javax.swing.text.Utilities (public class, everybody in the world can instantiate it)

  • com.sun.corba.se.impl.util.Utility (public JDK internal class, though you should not directly use it)
PS: I should also add this caution: don't add a private no-arg constructor to existing util classes. Doing so will break all the clients that are using this implicit public no-arg constructor. It also makes this util class no longer inheritable, and so none of its subclasses will compile or run. The best you can do is probably add a @Deprecated public no-arg constructor with some sort of warning messages.

Are these classes so-called static classes? Well, there is no such term "static class" in java, and no top-level class can be static. There are only classes with static methods. Of course, an inner class can be static.

Followers

Pageviews Last 7 Days