Rules and use of Private Constructor:
1) Private Constructor is used when you don’t want to create an object for the class. These are commonly used in classes that contain static members only. If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class.
2) We cannot inherit from classes that are having only private constructors. The reason is suppose if you are inheriting from a base class which has only private constructors and if you create an object for the derived class then the base class constructor will be called. Because the base class contains only private constructors and due to 'private' access modifier it is not accessible from the derived class. So it will give you an error with a syntax as follows Console Application ’ is inaccessible due to its protection level’
3) Where do you find Private constructors are useful?
Private constructors can also be useful for: classes containing only static utility methods classes containing only constants type safe enumerations.
If we want to create object of class even if we have private constructors then we need to have public constructor along with private constructor.
Let’s understand by an example:
class Program
{
public class MysampleClass
{
public string param1, param2;
public MysampleClass(string a, string b) //Public Parameterized Constructor.
{
param1 = a;
param2 = b;
}
private MysampleClass() // Private Constructor Declaration without parameter.
{
Console.WriteLine("Private Constructor Declaration with no parameter");
}
}
class MyProgram
{
static void Main(string[] args)
{
MysampleClass objMysampleClass = new MysampleClass("Vikas","Verma");
Console.WriteLine(objMysampleClass.param1 +" " + objMysampleClass.param2);
// //It will be inaccessible due to it protection level (without parameter)
MysampleClass obj = new MysampleClass();
Console.ReadLine();
}
} }


0 comments:
Post a Comment
Note: only a member of this blog may post a comment.