In this quick tutorial, we will discuss about private constructor in Java, its uses. How to declare a private constructor and call a private constructor in Java?

Before we answer that let’s make the basics clear. Java is an Object Oriented Programming language. It uses a predefined template called Class to create objects. Class is also referred to as an object factory.

person class java

Class to create objects

A class contains data and methods together which can be accessed/used by creating an object of that class.

Well, then what is the story of Constructors?

A constructor is a special method in Java that is used to initialize Objects. As we mentioned that to use the members and methods of a class we need to create an object! This is how we create an object in Java.

Classname obj = new Classname();

Probably you have seen this before. But if you don’t know what a Constructor is? You might not know the purpose of the parenthesis'()’ at the end of the Classname. Every Class in Java has a default constructor! The statement ‘Classname( )‘ executes the default constructor of a class.

public class ConstructorDemo {
	int var;
    ConstructorDemo() {
	/*this ia a default constructor 
        in Java. Whether we write it or 
        not, it is already defined!*/
    }
    
    void show() {
    	System.out.println("hello world! my variable- "+var);
    }
}
//Creating object of class ConstructorDemo
public class Test {
	public static void main(String[] args) {
		ConstructorDemo obj = new ConstructorDemo();
		obj.show();
	}
}

OUTPUT

hello world! my variable- 0

Use of Java Constructor

A java constructor is used to initialize the member variables of a class. In the above example, we used a variable named 'var'. But when the show method is called from the main method of the Test class the value of my variable is printed as 0. This is because we did not initialize var in the ConstructorDemo class and 0 is the default value of an int in Java. To solve this we can use a parameterized constructor. Here’s how.

public class ConstructorDemo {
	int var;
    ConstructorDemo(int value) {
    	var = value;
    }
    
    void show() {
    	System.out.println("hello world! my variable- "+var);
    }
}

As soon as we make changes in the ConstructorDemo class the Test class will show an error! It will say that ‘ConstructorDemo( )’ is not defined! The fact is that when we create our own parameterized constructor, the default constructor is removed! So to solve this we can do 2 things.

Either mention a default non-parameterized constructor for ConstructorDemo class or avoid calling the constructor with no parameters! Definitely, the first way is more authenticate.

Test Class:

public class Test {
	public static void main(String[] args) {
		ConstructorDemo obj = new ConstructorDemo(5);
		obj.show();
	}
}

OUTPUT

hello world! my variable- 5

Constructor vs Methods

The purpose of a constructor is to initialize the object of a class while the purpose of a method is to perform a task by executing java code. Constructors cannot be abstract, final, static, and synchronized while methods can be. Constructors do not have return types while methods do.

Private Constructors

Singleton class Private Constructor in Java

Singleton class

By declaring a private constructor in Java, we are restricting its object creation of that class. A class does not have a real-life existence but an object does. It might occur that we need a limited object of a class.

Let’s say we are about to play a game! And objects of Players are being created. But our game allows only one player at a time. In this scenario, a Singleton class will be a solution. But our game can also be played by 2/3/4 players! What then? Well, we control the number of Player objects created in this way:

Player Class

public class Player {
	private static int playercount;
	
	String name;
	int id;
	
    private Player(String name,int id) {//private constructor in java is not visible to any other class!
    	this.name = name;
    	this.id = id;
    }
    
    void showPlayerInfo() {
    	System.out.println("player_"+id+": "+"name = "+name);
    }
    
    static Player getPlayer(String name, int id) {
    	playercount++;
    	if(playercount > 1) {//set max player count
    		System.out.println("Max player limit reached!");
    		return null;
    	}
    	return new Player(name,id);
    }
}

Caller Class

public class Singleton {
	public static void main(String[] args) {
		Player p1;
		p1 = Player.getPlayer("Toto", 1);
		p1.showPlayerInfo();
		
		Player p2;
		p2 = Player.getPlayer("Shuvo", 2);
	}
}

OUTPUT

player_1: name = Toto
Max player limit reached!