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();
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
getInstanceallows 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
newoperator 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.