[java] How can I create an utility class?

I want to create a class with utility methods, for example

public class Util {

   public static void f (int i) {...}

   public static int g (int i, int j) {...}

}

Which is the best method to create an utility class?

Should I use a private constructor?

Should I make the utility class for abstract class?

Should I do nothing?

This question is related to java utility utility-method

The answer is


According to Joshua Bloch (Effective Java), you should use private constructor which always throws exception. That will finally discourage user to create instance of util class.

Marking class abstract is not recommended because is abstract suggests reader that class is designed for inheritance.


Making a class abstract sends a message to the readers of your code that you want users of your abstract class to subclass it. However, this is not what you want then to do: a utility class should not be subclassed.

Therefore, adding a private constructor is a better choice here. You should also make the class final to disallow subclassing of your utility class.


I would make the class final and every method would be static.

So the class cannot be extended and the methods can be called by Classname.methodName. If you add members, be sure that they work thread safe ;)