Should Helper/Utility Classes be abstract?

Don't bother making them abstract, but include a private parameterless constructor to prevent them from ever being instantiated.

Point of comparison for those interested: in C# you would declare the class to be static, making it abstract and sealed (Java's final) in the compiled form, and without any instance constructor at all. That also makes it a compile-time error to declare a parameter, variable, array etc of that type. Handy.


You could just declare a private constructor that does nothing.

The problem with declaring the class "abstract" is that the abstract keyword usually means that class is intended to be subclassed and extended. That's definitely not what you want here.


I don't declare utility classes abstract, I declare them final and make the constructor private. That way they can't be subclassed and they can't be instantiated.



public final class Utility
{
    private Utility(){}

    public static void doSomethingUseful()
    {
        ...
    }
}

I would add more step beyond the private constructor:

public class Foo {
   // non-instantiable class
   private Foo() { throw new AssertionError(); }
}

Throwing the AssertionError prevents methods in the same class from instantiating the class (well, they can try). This isn't normally a problem but in a team environment you never know what someone will do.

As regards the "abstract" keyword, I have noticed utilities classes subclassed in numerous instances:

public class CoreUtils { ... }
public class WebUtils extends CoreUtils { ... }

public class Foo { ... WebUtils.someMethodInCoreUtils() ... }

I believe this is done so that people don't have to remember which utility class to include. Are there any downsides to this? Is this an anti-pattern?

Regards, LES