1

I have read about private constructors on many websites, and also referred various questions on StackOverflow. However, I failed to understand their usage. Most websites say that a private constructor can be used when we want to restrict the number of instances of objects that can be created.

I tried the following program:

public class PrivateCons{
   private PrivateCons(){
    System.out.println("I'm executed");
   }

   public static void main(String[] args) {
      PrivateCons p=new PrivateCons();
      PrivateCons q=new PrivateCons();
   }
}

My program executes perfectly well. Have I understood the concept wrong?

1
  • 1
    Your main method is inside your class that has the private constructor. So only you - as the developer of that class - have the authority of creating instances of it, and thus can restrict their number to what you want. If you provide your class as part of a library and give it to me, then I am not allowed to create instances. This is usually a concept for singletons or classes that provide static factory methods. Commented Nov 5, 2014 at 7:53

4 Answers 4

2

Private fields are accessible from within the class, you cannot access them out of class for example:-

class PrivateCons{
   private PrivateCons(){
    System.out.println("I'm executed");
   }
}

public class Test{
   public static void main(String[] args) {
      PrivateCons p=new PrivateCons(); //this will fail- compiler error
      PrivateCons q=new PrivateCons();//this will fail- compiler error
   }
}

Also Private constructors are mostly used for implementing Singleton Pattern , this is used when only one object of that class is needed. Taking an example from the wikipedia article in the link itself:-

public class singleton
{
    private static singleton _obj;

    private singleton()
    {
        // prevents instantiation from external entities
    }

    // Instead of creating new operator, declare a method
    // and that will create object and return it.

    public static singleton GetObject()
    {
        // Check if the instance is null, then it
        // will create new one and return it.
        // Otherwise it will return previous one.

        if (_obj == null)
        {
            _obj = new singleton();
        }

        return _obj;
    }

}

You can extend this example and restrict your objects to 2,3 or any number, Or in other words restrciting number of instances of your class.

Sign up to request clarification or add additional context in comments.

2 Comments

Keep in mind that the Singleton Pattern limits your code. With the Singleton pattern you can't have your main build and UnitTests parallel, since the UnitTests use the same instance. Also, when you want to make future adjustments, like having multiple instances of the Singleton class, this also give problems. (For example: I have a class Anthill and a class Ant. Anthill can be a Singleton and you have a bunch of Ant-objects. Let's say that in the future I want to have multiple Anthills. Now this isn't possible anymore without changing the code completely, since only 1 Anthil-instance can exist
Yes thats true, but there are valid uses of Singleton pattern too, for example java.lang.Runtime uses Singleton pattern.
1

From within the same class, you have access to the private constructor. From other classes, you can't call that constructor.

You can use a private constructor to implement the Singleton design pattern.

public class PrivateCons
{
   PrivateCons instance = new PrivateCons ();
   private PrivateCons(){
    System.out.println("I'm executed");
   }
   public static PrivateCons getInstance()
   {
       return instance;
   }
}

Now, users of your class can only obtain a single instance of your class, via the getIstnace method, since they can't create new instances via the private constructor.

3 Comments

This is not really th best way to create singletons... i would use an other code example..
Thanks :) Could you please tell me how would you call the getInstance() method here. I tried a few ways, but they gave me errors.
@user2195963 It's a static method, so you call it this way : PrivateCons.getInstance()
1

A private constructor doesn't restrict the number of instances created; it restricts where the constructor may be called.

It prevents the constructor from being called from outside the scope of the top-level class (in this case, PrivateCons).

Comments

0

Please take a look at the folloing example:

public class ClassWithPrivateConstructor {

private static final Random random = new Random();
private static final int count = 10;
private static final ClassWithPrivateConstructor[] instances = new ClassWithPrivateConstructor[count]; 
static    
{
    for (int i = 0; i < count; i++) {
        instances[i] = new ClassWithPrivateConstructor();
    }
}

public static ClassWithPrivateConstructor newInstance() {
    return instances[random.nextInt(count)];
}

private ClassWithPrivateConstructor() {        
}
}

Test class:

public class ClassWithPrivateConstructorTest {
public static void main(String[] args) {
    for(int i=0;i<20; ++i) {
        System.out.println(ClassWithPrivateConstructor.newInstance());
    }
}
}

Example output: ClassWithPrivateConstructor@14ae5a5 ClassWithPrivateConstructor@7f31245a ClassWithPrivateConstructor@7f31245a ClassWithPrivateConstructor@14ae5a5 ClassWithPrivateConstructor@6d6f6e28 ClassWithPrivateConstructor@7f31245a ClassWithPrivateConstructor@14ae5a5 ClassWithPrivateConstructor@135fbaa4 ClassWithPrivateConstructor@6d6f6e28 ClassWithPrivateConstructor@45ee12a7 ClassWithPrivateConstructor@330bedb4 ClassWithPrivateConstructor@45ee12a7 ClassWithPrivateConstructor@7f31245a ClassWithPrivateConstructor@135fbaa4 ClassWithPrivateConstructor@14ae5a5 ClassWithPrivateConstructor@2503dbd3 ClassWithPrivateConstructor@6d6f6e28 ClassWithPrivateConstructor@4b67cf4d ClassWithPrivateConstructor@7ea987ac ClassWithPrivateConstructor@45ee12a7

As you can see the number of class instances is limited in this case to 10.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.