Search code examples
oopconstructorprivate-members

Proper use of private constructors


I was reading about private constructor and found a few points that I couldn't understand. It said, if you declare a constructor as private:

  1. That class cannot be explicitly instantiated from another class
  2. That class cannot be inherited
  3. Should be used in classes containing only static utility methods

My first question: Point 2 says the class cannot be inherited. Well, if you declare a class private then it would still satisfy this property. Is it because, if a class is private, it can still be explicitly instantiated from outside by another class?

My second question: I don't understand point 3. If I have a helper class which is full of static methods, I would never have to instantiate that class to use the methods. So, what is the purpose of a constructor in that class which you are never going to instantiate?


Solution

  • Answer for Java

    Question 1 You're confusing a private class, with a class that has a private constructor. Private constructors are used mainly for static classes that are not meant to be instatiated (i.e. they just have a bunch of static methods on them).

    Question 2 Exactly there is no need for a constructor so you have to explicitly create a private constructor so that it does not get a default constructer that the JVM will provide if none is defined

    An empty class with no methods defined will always be given a no argument constructor by the JVM by default