Add a private constructor to hide the implicit public one. Open
public class Security {
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Utility classes, which are collections of static
members, are not meant to be instantiated. Even abstract utility classes, which can
be extended, should not have public constructors.
Java adds an implicit public constructor to every class which does not define at least one explicitly. Hence, at least one non-public constructor should be defined.
Noncompliant Code Example
class StringUtils { // Noncompliant public static String concatenate(String s1, String s2) { return s1 + s2; } }
Compliant Solution
class StringUtils { // Compliant private StringUtils() { throw new IllegalStateException("Utility class"); } public static String concatenate(String s1, String s2) { return s1 + s2; } }
Exceptions
When class contains public static void main(String[] args)
method it is not considered as utility class and will be ignored by this
rule.
All methods are static. Consider using a utility class instead. Alternatively, you could add a private constructor or make the class abstract to silence this warning. Open
public class Security {
public static final String SHA256_ALGORITHM = "SHA-256";
public static String createHash(String str) {
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
UseUtilityClass
Since: PMD 0.3
Priority: Medium
Categories: Style
Remediation Points: 50000
For classes that only have static methods, consider making them utility classes. Note that this doesn't apply to abstract classes, since their subclasses may well include non-static methods. Also, if you want this class to be a utility class, remember to add a private constructor to prevent instantiation. (Note, that this use was known before PMD 5.1.0 as UseSingleton).
Example:
public class MaybeAUtility {
public static void foo() {}
public static void bar() {}
}