Sometimes, it's useful to have a class that only contains static methods and static fields.
For example, you can use utility classes like `java.lang.Math`, `java.util.Arrays` that group together methods related to mathematical operations or arrays. Or, you can gather static factory methods that create objects implementing a specific interface, such as `java.util.Collections`.
These utility classes don't require a constructor because they can be used without instance variables or methods. However, if you don't explicitly define a constructor, the compiler automatically generates a public default constructor. This makes it difficult for users to distinguish whether the constructor is automatically generated.
To prevent this, some developers create the class as an abstract class. However, abstract classes don't prevent instantiation. You can simply create a subclass and instantiate it.
Therefore, to prevent instantiation of a utility class, you should make the constructor's access modifier `private`.
If the default constructor's access modifier is `private`, it cannot be accessed from outside the class. Additionally, it throws an exception if the default constructor is called internally.
Using a `private` constructor can be difficult for users to understand, so adding comments is also a good practice. As a side note, making a constructor `private` also prevents inheritance.
Comments0