views:

643

answers:

10

Can a constructor be private? How is a private constructor useful?

+4  A: 

Yes.

This is so that you can control how the class is instantiated. If you make the constructor private, and then create a visible constructor method that returns instances of the class, you can do things like limit the number of creations (typically, guarantee there is exactly one instance) or recycle instances or other construction-related tasks.

Doing new x() never returns null, but using the factory pattern, you can return null, or even return different subtypes.

You might use it also for a class which has no instance members or properties, just static ones - as in a utility function class.

lavinio
@lavinio, but you could keep track of the number of instances simply by using a static variable; it isn't necessary to make the constructor private for that.
Michael Aaron Safyan
@michael indeed you can, but it is not as elegant, and the restriction is not as obvious to the users of the class.
Jon
@Jon, sorry, I misunderstood... I thought you were merely counting the number of instances, not restricting the number of instances.
Michael Aaron Safyan
A: 

Private constructors prevent a class from being explicitly instantiated by callers see further information on PrivateConstructor

GustlyWind
+15  A: 

Yes, a constructor can be private. There are different uses of this. One such use is for the singleton design anti-pattern, which I would advise against you using. Another, more legitimate use, is in delegating constructors; you can have one constructor that takes lots of different options that is really an implementation detail, so you make it private, but then your remaining constructors delegate to it.

As an example of delegating constructors, the following class allows you to save a value and a type, but it only lets you do it for a subset of types, so making the general constructor private is needed to ensure that only the permitted types are used. The common private constructor helps code reuse.

public class MyClass
{
     public MyClass(int x){
         this(Integer.toString(x),"int");
     }

     public MyClass(boolean x){
         this(Boolean.toString(x),"boolean");
     }

     private MyClass(String value, String type){
         _value = value;
         _type = type;
     }

     public String toString(){
         return _value;
     }

     public String getType(){
         return _type;
     }

     private String _value;
     private String _type;
}
Michael Aaron Safyan
What's wrong with singletons?
Vuntic
from a testability point of view - they represent a global state, which is hard to predict (and test)
Bozho
@Vuntic, please see: http://sites.google.com/site/michaelsafyan/coding/design/coding-best-practices/avoid-global-variables-environment-variables-and-singletons
Michael Aaron Safyan
@Vuntic, the short answer is that singletons result in shared mutable state and, more importantly, baking the singleton-ness into the API makes it inflexible, makes it hard to test, and makes things like hell when it turns out that the singleton assumption is not correct. While it is fine to have singletons in the sense that you only instantiate the object once, enforcing singleton-ness via private constructor and static instantiation function leads to an incredibly messy and fragile design. A better approach is to pass around the interface that the singleton conforms to...
Michael Aaron Safyan
... and to construct only one instance of it, and then pass it around. This approach is known as dependency injection, and leads to cleaner, more flexible designs.
Michael Aaron Safyan
The real anti-pattern here is overusage imho. This applies to any pattern that is used out of habit without giving thought to what is best in the given situation.
rsp
I've just lately been diving into openGL... if you think singletons are evil, good GOD you'll hate that... currently about 80% of my mini-program to test that stuff is in either singletons or static methods. This is not a bad thing.
Vuntic
+8  A: 

Yes it can. A private constructor would exist to prevent the class from being instantiated, or because construction happens only internally, e.g. a Factory pattern. See here for more information.

Feanor
+1  A: 

Yes and it is used to prevent instantiation and subsequently overriding. This is most often used in singleton classes.

Vaishak Suresh
+6  A: 

I expected that someone would've mentioned this (the 2nd point), but.. there are three uses of private constructors:

  • to prevent instantiation outside of the object, in the following cases:

    • singleton
    • factory method
    • static-methods-only (utility) class
    • constants-only class
      .
  • to prevent sublcassing (extending). If you make only a private constructor, no class can extend your class, because it can't call the super() constructor. This is some kind of a synonym for final

  • overloaded constructors - as a result of overloading methods and constructors, some may be private and some public. Especially in case when there is a non-public class that you use in your constructors, you may create a public constructor that creates an instance of that class and then passes it to a private constructor.

Bozho
@Bozho, in Java, the keyword "final" is used to prevent subclassing; it is not necessary to make the constructor private for that.
Michael Aaron Safyan
it is not necessary, but you can. I mentioned the `final` keyword as a way to achieve this.
Bozho
+3  A: 

Private Constructors can be defnied in the Java for the following reasons

  1. To have control on the instantiation of the Java objects, it wont allow you to create an instance of an object.

  2. It wont allow the class to be Subclassed

  3. This has a special advantage when implementing the singleton Pattern, Private contstructors are used for it and have a control on the creating the instance for the whole application.

  4. when you want to have a class with all constants defined and Does not require its instance any more, then we declare that class as a private constructor.

harigm
+3  A: 

Some reasons where you may need private constructor: The constructor can only be accessed from static factory method inside the class itself. Singleton can also belong to this category. A utility class, that only contains static methods.

giri
+2  A: 

Yes.

A private constructor is used to prevent instance initializing, such as the Math final class you use in java. Singleton also use private constructor

ryf9059
A: 

Basic idea behind having a private constructor is to restrict the instantiation of a class from outside by JVM, but if a class having a argument constructor, then it infers that one is intentionally instantiating.

Phani