CodesJava

Easy learning with example program codes

what is the use of 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.codesjava;
 
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 main method

Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki