We can create private constructor in java. It is used to restrict the instantiation of a class. We cannot create an object outside of the class, if we create the private constructor. It is used to implement Singleton pattern. The main purpose of singleton pattern is to control object creation i.e. keep only one instance of a class at any time.
Example
package com.w3schools; public class Test { private static Test object = null; private Test() { //private constructor } public Test getObject() { //Creating object using private constructor if(object == null) { object = new Test(); } return object; } } |
Java interview questions on constructor
- Default constructor
- Does constructor return any value in java?
- Is constructor inherited in java?
- Can you make a constructor final in java?
- Difference between constructor and method in java?
- How to copy values from one object to another java?
- How to overload constructor in java?
- can you create an object without using new operator in java?
- Constructor chaining in java
- Parameterized constructor in java
- Can we call subclass constructor from superclass constructor?
- What happens if you keep return type for a constructor?
- What is the use of private constructor in java?
- Can a constructor call another constructor java?