This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes private constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "private constructor" Watch "private constructor" New topic
Author

private constructor

Prashanth Lingala
Ranch Hand

Joined: Nov 13, 2004
Posts: 66

Constructors can use any access modifier, including private. (A private
constructor means only code within the class itself can instantiate an object of that type, so if the private-constructor class wants to allow an instance of the class to be used, the class must provide a static method or variable that allows access to an instance created from within the class.)


Can somebody explain this, if feasible demonstrate with a simple example...

Source: Sun certified programmer and developer exam

Thanking in advance

Regards
Prashanth Lingala


Have A Nice Day !!!
Mehul Sanghvi
Ranch Hand

Joined: Feb 04, 2002
Posts: 134
Hi,

This is what Factory Pattern is all about.

Where in for some reason you as the writer of the class do not want the user classes to instantiate objects of your class directly. Hence you ask the users of your class to call a static method defined within your class which in turn may do some validation and then may return a new object of your class or may return a reference to singleton.

Example code for plain factory pattern:


Example code for singleton factory pattern:


Factory pattern can be taken further to achieve the following:
Georgy Bolyuba
Ranch Hand

Joined: Feb 18, 2005
Posts: 162

[ February 21, 2005: Message edited by: George Bolyuba ]

SCJP 1.4 (100%) Done.<br />SCJD (URLyBird 1.2.3 Started)
Prashanth Lingala
Ranch Hand

Joined: Nov 13, 2004
Posts: 66
I will go through it, this topic is new to me, let me burn it in...

Thanks for all who chipped in...

Regards
Prashanth Lingala
 
Consider Paul's rocket mass heater.
 
subject: private constructor
 
Similar Threads
private constructor
Constructor Rules
Marcus exam Q30
constructor doubt
Is it possible for a class to have a private constuctor???