+ 3
PRIVATE CONSTRUCTORS
I just came to know that constructors can be declared private. Please tell me the uses of a private Constructor. An Example would be appreciated. Thanks.
5 ответов
+ 8
Search for Singleton pattern on Google. Singleton is used if only one instance of a class is allowed. That is realised by a private constructor, that can only be invoked by a public method of the class, which tests if the class is already instantiated and only invokes the constructor if it isn't.
+ 9
Private constructors are used to prevent creating instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class. If all the methods in the class are static, consider making the complete class static.
You can also use them to initialize some standard set of fields before other constructors.
In C#, An Example Class Code will be like :
public class Sample
{
int x, y, z;
string name;
bool flag;
private Sample()
{
x = 5;
y = 10;
z = 15;
flag = true;
}
public Sample(string Name)
: this()
{
//flag, x, y, and z are initialized here
name = Name;
}
public Sample(string Name, bool flag)
: this(Name) //Constructor chaining
{
//name, flag, x, y, and z are initialized here, but we need to change flag
this.flag = flag;
}
}
+ 8
[This comes under OOP Concept!]
The use of private constructor is to serve singleton classes. A singleton class is one which limits the number of objects creation to one. Using private constructor we can ensure that no more than one object can be created at a time.
In Java, the Example Code is (as Given) :
public class SingleTonClass {
//Static Class Reference
private static SingleTonClass obj=null;
private SingleTonClass(){
/*Private Constructor will prevent
* the instantiation of this class directly*/
}
public static SingleTonClass objectCreationMethod(){
/*This logic will ensure that no more than
* one object can be created at a time */
if(obj==null){
obj= new SingleTonClass();
}
return obj;
}
public void display(){
System.out.println("Singleton class Example");
}
public static void main(String args[]){
//Object cannot be created directly due to private constructor
//This way it is forced to create object via our method where
//we have logic for only one object creation
SingleTonClass myobject= SingleTonClass.objectCreationMethod();
myobject.display();
}
}
|
| The Output Will Be :
| Singleton class Example
|
+ 6
Probably one use is to stop copying of objects if you make copy constructor private.
+ 2
Thanks @Tashi and @Megatron