Private Constructor

Few years ago

I recalled a story today. When I was studying university, I asked my Professor who taught Java:

What is the use of private constructor?

He didn’t have the answer. We thought of a few possibilities but weren’t so sure about them at the end of the day.

The Private Constructor

We cannot instantiate MyClass outside it. new MyClass() can only be called inside  MyClass. Is it useless?

The Singleton Pattern

Turns out the private constructor is useful for the singleton pattern to avoid other classes instantiating the singleton on their own.

From this, we can restrict the  MySingleton class instantiates at most once throughout the run time of the application.

singleton

In bridge, it is also called Singleton if the hand contains only 1 card of a suit.

 

If you like my post, please give a little help to share it!
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0