Reputation: 25
I learned that static methods are used to create an instance of a class type. I see that some classes using static method have to declare a private constructor for that class.
What is the use of private constructor? Can we still create an instance of a class without using the private constructor? Thanks.
Upvotes: 0
Views: 56
Reputation: 2577
Basically we use this kind of static factory method in Singleton Design Pattern.
Singleton means based on this design pattern we can create only one object for the class.
for Example:
class Test{
private static Test mObject;
private Test()
{
}
public static Test getInstance(){
if(mObject==null){
mObject=new Test();
}
return mObject;
}
}
Upvotes: 1
Reputation: 15708
What is the use of Private Constructor?
If a class has only private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class
Can we still create an instance of a class without using Private Constructor
Yes using reflection (need to call setAccessible of constructor)
Upvotes: 0