Awani
Awani

Reputation: 404

Creating objects of a class with private constructor

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?

Upvotes: 1

Views: 3431

Answers (4)

BlueLettuce16
BlueLettuce16

Reputation: 2103

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.

Upvotes: 0

Mustafa sabir
Mustafa sabir

Reputation: 4360

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.

Upvotes: 2

Chris Martin
Chris Martin

Reputation: 30756

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).

Upvotes: 1

Eran
Eran

Reputation: 394126

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.

Upvotes: 1

Related Questions