What is a private constructor? Where will you use it?

 Posted by Virendradugar on 9/7/2009 | Category: OOPS Interview questions | Views: 14901
Answer:

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.


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Posted by: SurajRane on: 11/4/2009
we can use private constructor in some cases like

while designing singleton classes

here is a simple code for singleton class



public class Singelton

{
public int k;

private Singelton()
{
}


private static Singelton Obj = new Singelton();

public static Singelton GetSingleTonObject()
{
return Obj;
}

public void M1() { }
//Code other methods
}



Login to post response

More Interview Questions by Virendradugar