Example 1: Java program to create a private constructor
class Test {
// create private constructor
private Test () {
System.out.println("This is a private constructor.");
}
// create a public static method
public static void instanceMethod() {
// create an instance of Test class
Test obj = new Test();
}
}
class Main {
public static void main(String[] args) {
// call the instanceMethod()
Test.instanceMethod();
}
}
Output
This is a private constructor.
In the above example, we have created a private constructor of the Test
class. Hence, we cannot create an object of the Test
class outside of the class.
This is why we have created a public static
method named instanceMethod()
inside the class that is used to create an object of the Test class. And from the Main
class, we call the method using the class name.
Example 2: Java Singleton design using a private constructor
The Java Singleton design pattern ensures that there should be only one instance of a class. To achieve this we use the private constructor.
class Language {
// create a public static variable of class type
private static Language language;
// private constructor
private Language() {
System.out.println("Inside Private Constructor");
}
// public static method
public static Language getInstance() {
// create object if it's not already created
if(language == null) {
language = new Language();
}
// returns the singleton object
return language;
}
public void display() {
System.out.println("Singleton Pattern is achieved");
}
}
class Main {
public static void main(String[] args) {
Language db1;
// call the getInstance method
db1= Language.getInstance();
db1.display();
}
}
Output
Inside Private Constructor Singleton Pattern is achieved
In the above example, we have created a class named Languages. The class contains,
- language - class type
private
variable - Language() -
private
constructor - getInstance() -
public static
class type method - display() -
public
method
Since the constructor is private
, we cannot create objects of Language from the outer class. Hence, we have created an object of the class inside the getInstance()
method.
However, we have set the condition in such a way that only one object is created. And, the method returns the object.
Notice the line,
db1 = Language.getInstance();
Here,
- db1 is a variable of Language type
- Language.getInstance() - calls the method
getInstance()
Since, getInstance()
returns the object of the Language class, the db1 variable is assigned with the returned object.
Finally, we have called the display()
method using the object.