java – Hide Utility Class Constructor : Utility classes should not have a public or default constructor

java – Hide Utility Class Constructor : Utility classes should not have a public or default constructor

If this class is only a utility class, you should make the class final and define a private constructor:

public final class FilePathHelper {

   private FilePathHelper() {
      //not called
   }
}

This prevents the default parameter-less constructor from being used elsewhere in your code. Additionally, you can make the class final, so that it cant be extended in subclasses, which is a best practice for utility classes. Since you declared only a private constructor, other classes wouldnt be able to extend it anyway, but it is still a best practice to mark the class as final.

I dont know Sonar, but I suspect its looking for a private constructor:

private FilePathHelper() {
    // No-op; wont be called
}

Otherwise the Java compiler will provide a public parameterless constructor, which you really dont want.

(You should also make the class final, although other classes wouldnt be able to extend it anyway due to it only having a private constructor.)

java – Hide Utility Class Constructor : Utility classes should not have a public or default constructor

I use an enum with no instances

public enum MyUtils { 
    ; // no instances
    // class is final and the constructor is private

    public static int myUtilityMethod(int x) {
        return x * x;
    }
}

you can call this using

int y = MyUtils.myUtilityMethod(5); // returns 25.

Leave a Reply

Your email address will not be published.