Can we declare a constructor as private in Java?

JavaObject Oriented ProgrammingProgramming

Yes, we can declare a constructor as private. If we declare a constructor as private we are not able to create an object of a class. We can use this private constructor in the Singleton Design Pattern.

Conditions for Private Constructor

  • A private constructor does not allow a class to be subclassed.
  • A private constructor does not allow to create an object outside the class.
  • If all the constant methods are there in our class we can use a private constructor.
  • If all the methods are static then we can use a private constructor.
  • If we try to extend a class which is having private constructor compile time error will occur.

Example

Live Demo

class SingletonObject {
   private SingletonObject() {
      System.out.println("In a private constructor");
   }
   public static SingletonObject getObject() {
      // we can call this constructor
      if (ref == null)
         ref = new SingletonObject();
      return ref;
   }
   private static SingletonObject ref;
}
public class PrivateConstructorDemo {
   public static void main(String args[]) {
      SingletonObject sObj = SingletonObject.getObject();
   }
}

Output

In a private constructor
raja
Published on 27-Jun-2019 17:24:07
Advertisements