In this article, we will understand how to implement private constructors. Private constructors allow us to restrict the instantiation of a class.
Below is a demonstration of the same −
Input
Suppose our input is −
Run the program
Output
The desired output would be −
Private constructor is being called
Algorithm
Step 1 - Start Step 2 - We define a private constructor using the ‘private’ keyword. Step 3 - Making a constructor private ensures that an object of that class can’t be created. Step 4 - A private constructor can be used with static functions which are inside the same class. Step 5 - The private constructor is generally used in singleton design pattern. Step 6 - In the main method, we use a print statement to call the static method. Step 7 - It then displays the output on the console.
Example 1
Here, the input is being entered by the user based on a prompt.
class PrivateConstructor {
private PrivateConstructor () {
System.out.println("A private constructor is being called.");
}
public static void instanceMethod() {
PrivateConstructor my_object = new PrivateConstructor();
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Invoking a call to private constructor");
PrivateConstructor.instanceMethod();
}
}Output
Invoking a call to private constructor A private constructor is being called.
Example 2
Here, the a private instructor is invoked and an instance is called.
import java.io.*;
class PrivateConstructor{
static PrivateConstructor instance = null;
public int my_input = 10;
private PrivateConstructor () { }
static public PrivateConstructor getInstance(){
if (instance == null)
instance = new PrivateConstructor ();
return instance;
}
}
public class Main{
public static void main(String args[]){
PrivateConstructor a = PrivateConstructor .getInstance();
PrivateConstructor b = PrivateConstructor .getInstance();
a.my_input = a.my_input + 10;
System.out.println("Invoking a call to private constructor");
System.out.println("The value of first instance = " + a.my_input);
System.out.println("The value of second instance = " + b.my_input);
}
}Output
Invoking a call to private constructor The value of first instance = 20 The value of second instance = 20