Creating an abstract class or creating a private constructor

I have a question about design. Suppose if I have a class that has only static methods, what would be the best design option of the following two.

  • Make the class abstract
  • Make the constructor private, so no code outside the class can make an object of this class.

Does the choice depend on the situation or is there one better way? And why?

+7
java oop
source share
5 answers

Creating an abstract class assumes that you want this class to be inherited. If you want this to happen, make it abstract.

If you have only static methods (so this is some kind of utility class), then proceed with the second method.
Although there is nothing wrong with instantiating this class, since there is no benefit or disadvantage, it is best to make the constructor private to utility classes.

+9
source share

Let's see what the developers of the 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 the template here.

This makes sense, since an abstract class implies that the class must be subclassed, which is not the case when your class is a utility class that has only static methods.

+3
source share

I think the best approach is to create the final class using a private constructor. Because the purpose of an abstract class is to function as a base for subclasses.

+3
source share

Private designer 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 is reasonable to assume that you intended to inherit it, which does not apply to your description.

The final declaration guarantees that it cannot be extended.

+1
source share

I would say both.

Creating an abstract class prevents a potential user from creating his own instance even with reflection. This ensures that the user pays attention that this is a clean utility class and should not be created.

The constructor of an abstract class should never be publicly available. If the class is intended to be extended, the constructor must be protected, because in any case it can only be used by subclasses. But your class cannot be inherited. Therefore, its constructor can only be closed. Moreover, to be safe, the constructor may throw an IllegalStateException . In this case, even if someone in the future makes it publicly available, he cannot call it without changing his code.

+1
source share

All Articles