Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

making a class abstract vs making the constructor private

Tags:

java

oop

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?

like image 801
DesirePRG Avatar asked Apr 13 '15 07:04

DesirePRG


People also ask

What happens if I make class constructor private?

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.

Can the constructor be private in abstract class?

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.

Why would you make a constructor private?

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.

Should abstract classes be private?

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.


2 Answers

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.

like image 149
Loki Avatar answered Oct 31 '22 07:10

Loki


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.

like image 4
Eran Avatar answered Oct 31 '22 08:10

Eran