Reputation: 6378
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?
Upvotes: 7
Views: 788
Reputation: 363
I think the better approach is to create final class with a private constructor. Because The purpose of an abstract class is to function as a base for subclasses.
Upvotes: 4
Reputation: 4130
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.
Upvotes: 9
Reputation: 115328
I'd say "both".
Making the class abstract prevents potential user from creating its instance even using reflection. It guarantees that user pays attention that this is pure utility class and should not be instantiated.
Constructor of abstract class should never be public. If class is dedicated for extension the constructor should be protected because it anyway can be used by subclasses only. But your class cannot be inherited. Therefore its constructor can be only private. Moreover, to be on the safe side constructor can throw IllegalStateException
. In this case even if somebody in future makes it public he cannot call it without changing its code.
Upvotes: 1
Reputation: 393781
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.
Upvotes: 4
Reputation: 15415
Private constructor for sure. In general, a class with only static methods should be:
public final class Utility {
public static void foo() { }
// ... etc.
}
If you declared it abstract, it's reasonable to assume you intended it to be inherited, which is not the case from your description.
The final declaration ensures that it cannot be extended.
Upvotes: 2