What is the advantage in making the <font color=red>protected constructor </font>in a class
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   sabu_vs
Posted On:   Sunday, November 10, 2002 09:32 PM

Hi


Could you pls tell me What is the advantage in making the protected constructor in a class.

for eg: java.util.Calendar. We have to use Calendar.getInstance() method to get an instance.



Thanks

sabu

Re: What is the advantage in making the <font color=red>protected constructor </font>in a class

Posted By:   Anonymous  
Posted On:   Monday, November 11, 2002 09:15 AM

Calendar is an abstract class, so Calendar.getInstance() is implemented:


public static synchronized Calendar getInstance()
{
return new GregorianCalendar();
}


so it returns a GregorianCalendar, which is a concret class.

Protected constructors are for controlling how and when objects are instanciated, for example, if you want a class with one and only one instance in the system, you can do de following (it's call a singleton pattern):


class S {
protected S () { ... }
protected S theS = null;
static S getInstance() {
if (theS != null)
theS = new S();
return theS;
}
}


the trick is that clients of S can't instanciate S (because they can't access the constructor, so they cant do new S()), they have to use getInstance() and getInstance() guarantees that there are just one instance of S.

Re: What is the advantage in making the <font color=red>protected constructor </font>in a class

Posted By:   Lasse_Koskela  
Posted On:   Monday, November 11, 2002 12:01 AM

It's all about control. If there is a reason for you to limit the access, then you limit the access.


Usually (my best guess), the use of protected (or private) constructors and getInstance() methods is to maintain strict control over object instantiation. For example, the Calendar object you get might be a singleton...

About | Sitemap | Contact