Advanced Java Programming - Old Questions

6. Define the chain of constructor. What is the purpose of private constructor? [5]

5 marks | Asked in 2075

Chain of constructor is the process of calling one constructor from another constructor with respect to current object. Constructor chaining can be done in two ways: 

  • Within same class: It can be done using this() keyword for constructors in same class
  • From base class: by using super() keyword to call constructor from the base class

What is constructor chaining in Java

The main purpose of using a private constructor is to restrict object creation. We also use private constructors to implement the singleton design pattern. 

Example:

public class A  

{  

//craeting a private constructor   

private A()  

{  

}  

void display()  

{  

System.out.println("Private Constructor");  

}  

}  

private class Test  

{  

public static void main(String args[])  

{  

//compile time error  

A obj = new A();   

}  

}