Utility classes (classes consisting of static methods and static fields) are not designed to be instantiated. Despite this, I often see things that can be instantiated, so let's use a private constructor to make it absolutely impossible to instantiate.
If no constructor is defined, a constructor called the default constructor is automatically created.
By explicitly writing a private constructor, access from the outside is disabled and the generation of the default constructor is suppressed. AssertionError is not strictly necessary, but it is insured.
//Utility classes that cannot be instantiated
public class UtilityClass {
//Suppress the default constructor to prevent instantiation
private UtilityClass() {
throw new AssertionError();
}
… //The rest is omitted
}
[Read Effective Java] Chapter 2 Item 5 "Avoid the creation of unnecessary objects" https://qiita.com/Natsukii/items/ec64efddce85ffd59fa8
Recommended Posts