简体   繁体   中英

making a class abstract vs making the constructor private

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.

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

Does the choice depend on the situation or there is one best way to go? And why?

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM