Private constructor in java

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.w3spoint;
 
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

Please follow and like us:
Content Protection by DMCA.com