Advanced Java Programming - Old Questions
Question Answer Details
6. Define the chain of constructor. What is the purpose of private constructor? [5]
Answer
AI Generated Answer
AI is thinking...
Official Answer
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
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();
}
}