noMAD
noMAD

Reputation: 7844

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?

Upvotes: 0

Views: 162

Answers (2)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

I take and as an examples (not the best OO languages known, but very popular) - since you are not defining which languge do you mean.

Ad.2. In these languages you must either call superclass constructor explicitly or it is implicitly called for you. From a subclass you cannot call private methods (only public and protected) - this rule applies to constructors as well. This means if the class has only private constructors, there is no way to call one in subclass constructor. So you cannot subclass such class.

Ad. 3. It is just to avoid confusion - since this class is only a container for utility methods, there is no point in instantiating it. This way you can enforce this rule at compile time.

Upvotes: 1

Brad
Brad

Reputation: 15879

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

Upvotes: 1

Related Questions