I am a Java developer. In an interview I was asked a question about private constructors:
Can you access a private constructor of a class and instantiate it?
I answered 'No' but was wrong.
Can you explain why I was wrong and give an example of instantiating an object with a private constructor?
The basic premise for having a private constructor is that having a private constructor restricts the access of code other than own class' code from making objects of that class.
Yes we can have private constructors in a class and yes they can be made accessible by making some static methods which in turn create the new object for the class.
So to make an object of this class, the other class has to use the static methods.
What is the point of having a static method when we are making the constructor private?
Static methods are there so that in case there is a need to make the instance of that class then there can be some predefined checks that can be applied in the static methods before creation of the instance. For example in a Singleton class, the static method checks if the instance has already been created or not. If the instance is already created then it just simply returns that instance rather than creating a new one.
Yes, we can access the private constructor or instantiate a class with private constructor. The java reflection API and the singleton design pattern has heavily utilized concept to access to private constructor. Also, spring framework containers can access the private constructor of beans and this framework has used java reflection API. The following code demonstrate the way of accessing the private constructor.
I hope you got it.
Look at Singleton pattern. It uses private constructor.
We can not access private constructor outside the class but using Java Reflection API we can access private constructor. Please find below code:
If you are using Spring IoC, Spring container also creates and injects object of the class having private constructor.
One way to bypass the restriction is to use reflections:
I hope This Example may help you :
Output: private Constructor Called