Friday, 31 August 2012

What is a private constructor?

When you declare a Constructor with Private access modifier then it is called Private Constructor. We can use the private constructor in singleton pattern.
If you declare a Constructor as private then it doesn’t allow to create object for its derived class, i.e you loose inherent facility for that class.  

Example:
 Class A
 {
 // some code
Private Void A()
{
 //Private Constructor
 }
 }

 Class B:A
{
//code
 }
 B obj = new B();

// will give Compilation Error
Because Class A constructor declared as private hence its accessibility limit is to that class only, Class B can't access. When we create an object for Class B that constructor will call constructor A but class B have no rights to access the Class A constructor hence we will get compilation error.

No comments:

Post a Comment