Can A Java Class Constructor Be Private

      No Comments on Can A Java Class Constructor Be Private
Yes it can be done. In one of my previous post on Java interview questions, I added this question. Now here I’ll explain why; rather, when we need to declare a class constructor private.

The constructor of a java class can be private. To declare the constructor private, private keyword has to be used as usual. Most of the cases such classes do not have an overloded public constructor. Which means ability to instantiate an object of the class using new keyword is restricted. Often such classes are useful.

Suppose you have a class containing all your utility methods, used in application. Such a class can have a private constructor and the utility methods declared as static. This way, you can prevent instantiation of an object of the class, although all the utilitymethods can be called statically (by using ClassName.methodName()).

Example of Java Class with a private Constructor :

class AppUtilities {
 
   private AppUtilities(){
      // object instantiation blocked
   }
 
   public static void doSomething() {
      // utility method implementation here...
   }
 
   public static boolean doSomething() {
      // utility method implementation here...
      return true;
   }

}


Please follow and like us:
Pin Share

Leave a Reply

Your email address will not be published. Required fields are marked *