Exercise:
Write a Java Program to implement private constructor .
Click Here to View the Solution!
class PrivateConstructor {
private PrivateConstructor () {
System.out.println(
"Welcome to this private constructor.");
}
//declaring a public method
public static void instanceMethod() {
//create an instance of PrivateConstructor class
PrivateConstructor obj =
new
PrivateConstructor();
}
}
Public class Driver {
public static void main(String[] args) {
//call the instanceMethod()
PrivateConstructor.instanceMethod();
}
}
Click Here to View the Output!
Welcome to this private constructor.
Click Here to View the Explanation!
- This program is used to create a private constructor and implement it using a method.
- A class
PrivateConstructor
is created that will hold its private constructor which means that an object of this class cannot be created outside of the class. - To be able to call the constructor from outside of the class, a
public static void instanceMethod()
is created inside thePrivateConstructor
class that will hold the object of thePrivateConstructor
class. - Another class
Driver
is then created that will call theinstanceMethod()
holding the object of thePrivateConstructor
class using the name of the class asPrivateConstructor.instanceMethod()
.