I got a design question in my mind. Suppose if I have a class which has only static methods, what would be the best design option from the following two.
Does the choice depend on the situation or there is one best way to go? And why?
Private constructors allow us to restrict the instantiation of a class. Simply put, they prevent the creation of class instances in any place other than the class itself.
Answer: Yes. Constructors in Java can be private. All classes including abstract classes can have private constructors. Using private constructors we can prevent the class from being instantiated or we can limit the number of objects of that class.
Private constructors are used to prevent creating instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class. If all the methods in the class are static, consider making the complete class static.
But, incase of an abstract method, you cannot use it from the same class, you need to override it from subclass and use. Therefore, the abstract method cannot be private.
Making a class abstract assumes that you want this class to be inherited from. If you want this to happen, then make it abstract.
If you only have static Methods (so it's some kind of utility class) then go with the second way.
Though there is nothing wrong in creating an Instance of this class, as there is no benefit or disadvantage that way, the best practice is to make the constructor private for utility classes.
Let's look at what the developers of standard classes did :
public class Arrays {
// Suppresses default constructor, ensuring non-instantiability.
private Arrays() {
}
public class Collections {
// Suppresses default constructor, ensuring non-instantiability.
private Collections() {
}
I see a pattern here.
This makes sense, since an abstract class implies that the class should be sub-classed, which is not the case when your class is a utility class having only static methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With