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


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

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