can constructor be private?

here are three uses of private constructors:

  • to prevent instantiation outside of the object, in the following cases:
    • singleton
    • factory method
    • static-methods-only (utility) class
    • constants-only class
  • to prevent sublcassing (extending). If you make only a private constructor, no class can extend your class, because it can’t call the super() constructor. This is some kind of a synonym for final
  • overloaded constructors – as a result of overloading methods and constructors, some may be private and some public. Especially in case when there is a non-public class that you use in your constructors, you may create a public constructor that creates an instance of that class and then passes it to a private constructor.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s