Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do some classes restrict direct instantiation?

I have encountered various classes that don't allow creation of their instance directly. Rather we have to create their instance from some other class's static method or it own static method. For example:

B b = A.getB();

or

B b = B.getInstance();

What reason is behind that?

Why don't they allow creating instance directly, as in:

B b = new B();
like image 513
Yatendra Avatar asked Nov 22 '25 04:11

Yatendra


1 Answers

Some classes want to control the way in which they are instantiated, and so protect their constructors from public use. Use static factory methods like getInstance allows them to keep that control within their own code.

There are a million reasons for wanting to do this.

edit: To address your comment, this cannot be done inside the constructor because the new operator will always create a new instance (unless an exception is thrown). By the time the constructor is invoked, it's too late for the code in the constructor to control whether or not an object is instantiated.

like image 107
skaffman Avatar answered Nov 23 '25 20:11

skaffman