What’s the point of having a private constructor?

 

This may be news to you: in Java, it is possible to have a private constructor. Why one would want to use one is explored below.




The private modifier when applied to a constructor works in much the same way as when applied to a normal method or even an instance variable. Defining a constructor with the private modifier says that only the native class (as in the class in which the private constructor is defined) is allowed to create an instance of the class, and no other caller is permitted to do so. There are two possible reasons why one would want to use a private constructor – the first is that you don’t want any objects of your class to be created at all, and the second is that you only want objects to be created internally – as in only created in your class.

Private constructors can be used in the singleton design pattern

Why would you want objects of your class to only be created internally? This could be done for any reason, but one possible reason is that you want to implement a singleton. A singleton is a design pattern that allows only one instance of your class to be created, and this can be accomplished by using a private constructor.

You can read more about the Singleton design pattern here: Design pattern interview question 1.

Subscribe to our newsletter for more free interview questions.

Private constructors can prevent creation of objects




The other possible reason for using a private constructor is to prevent object construction entirely. When would it make sense to do something like that? Of course, when creating an object doesn’t make sense – and this occurs when the class only contains static members. And when a class contains only static members, those members can be accessed using only the class name – no instance of the class needs to be created.

Java always provides a default, no-argument, public constructor if no programmer-defined constructor exists. Creating a private no-argument constructor essentially prevents the usage of that default constructor, thereby preventing a caller from creating an instance of the class. Note that the private constructor may even be empty.

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.

  • Tim Trainor

    Yes you are right, the variable is not instantiated, it is just accessed as if it was.

  • donshon

    As I understand it, you’re not really instantiating it. You’re just referencing the class with a variable. That variable is never instantiated. Or am I missing something?

  • Wardroid

    you CAN, but you SHOULD NOT break contract.

  • Morris

    how its happening ?

  • karan

    how to creat the object of class contain private constructor??
    please give example code

  • Tim Trainor

    Ok. Create this class:

    public class CaptainPrivate {

    private CaptainPrivate() {

    }

    public static String doSomething() {
    return “something”;
    }
    }

    That’s got a private constructor.

    Then here is a junit test to prove that @Inject bypasses the private constructor.

    import javax.inject.Inject;
    import org.junit.Test;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;

    public class TestPrivateConstructor {

    private static final Logger logger = LoggerFactory.getLogger(TestPrivateConstructor.class);

    @Inject
    CaptainPrivate capnPrivate;

    @Test
    public void testPrivateConstructor() {
    String a = capnPrivate.doSomething();
    logger.info(a);
    }

    }

    The output will be
    TestPrivateConstructor.java 28 [main] INFO – something

    Proof? I believe so.
    That said, I’m not sure why you would do this. Nobody would. Just interesting to note that it is possible.

  • Malwinder Pal Singh

    Can you explain it with example?

  • Oliver Lockwood

    As per Josh Bloch’s Effective Java bible, I would tend to use a private constructor when implementing the Builder pattern, so that the `MyClass.Builder.build();` method has to be used to create instances of the class, instead of permitting e.g. `new MyClass();`.

  • Gopinath M B

    Good point on saying why designer dont want his user to create Object: As it has static members.

  • Tim Trainor

    You can still instantiate a java object that has a private constructor by using @javax.inject.Inject

    @Inject
    ObjectWithPrivateContructor object

    object.doStuff

    It works, try it out.

  • matt

    You can also use that in order to implement the Factory design pattern.