Can A Java Class Constructor Be Private

Written by Prithwiraj Bose on . Posted in Programming Tips Tricks Tutorials

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;
   }

}


Tags: , , , ,

Trackback from your site.

Prithwiraj Bose

I am working as an I.T. Analyst in TATA Consultancy Services. I live in Kolkata, India. I love computers, programming, travelling and singing. Photography, spending time with my aquarium, designing a random website, painting, and singing is my favorite pass time.

Leave a comment