Implement Private Constructor in Java


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()
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 the PrivateConstructor class that will hold the object of the PrivateConstructor class.
  • Another class Driver is then created that will call the instanceMethod() holding the object of the PrivateConstructor class using the name of the class as PrivateConstructor.instanceMethod().

%d bloggers like this: