Can java have Protected or Private Constructor

Hi,can java have Priavte or protected constructor,as we know java have default and public constructor ,and in using singleton design patters we can use private & protected constructor,so, what is the main logic,Regards,Prabhat
[279 byte] By [arpita_jsr08a] at [2007-10-3 0:08:53]
# 1

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.

YoGeea at 2007-7-14 16:57:49 > top of Java-index,Java HotSpot Virtual Machine,Specifications...
# 2

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 ?

prakash.skpa at 2007-7-14 16:57:49 > top of Java-index,Java HotSpot Virtual Machine,Specifications...
# 3

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();

}

}

Java@kondala at 2007-7-14 16:57:49 > top of Java-index,Java HotSpot Virtual Machine,Specifications...
# 4
In the case of default constructor it will be a no arg one, but in the case of protected you can have constructors that take arguments also.
alexbinua at 2007-7-14 16:57:49 > top of Java-index,Java HotSpot Virtual Machine,Specifications...