Yes, you can have a protected or private constructor. As you mentioned the singleton pattern is a common example where a constructor is declared as being private. Basically you use a private constructor to enforce noninstantiability. You use a protected constructor to prevent instantiation outside of the package.
Can u please explain the difference between default contructor and protected construtor ?
in the previous reply you have mentioned that protected constructor prevents the
object creation outside the package.. but the work of default cons also the same.. then why should we go for protected ?
Hi,
Yes, We can declare constructor as private/public/protected also.
Having only private constructors means that you can't instantiate the class from outside the class (although instances could still be created from within the class - more about this later). However, when you instantiate a class, you must first initialize all superclasses of that class by invoking their constructors. If one of the superclasses has only private constructors declared, we have a problem. We can't invoke the superclass' constructor which means that we can't instantiate our object. Because of this, we've essentially made a class that can't be extended.
example:
class TheWorld
{
private static TheWorld _instance = null;
private TheWorld() {}
public static TheWorld instance()
{
if ( _instance == null )
{
_instance = new TheWorld();
}
return _instance;
}
public void spin() {...}
}
public class WorldUser
{
public static void main(String[] args)
{
TheWorld.instance().spin();
}
}