File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "private constructor" Watch "private constructor" New topic

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

Prashanth Lingala

Have A Nice Day !!!
Mehul Sanghvi
Ranch Hand

Joined: Feb 04, 2002
Posts: 134

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...

Prashanth Lingala
I agree. Here's the link:
subject: private constructor
It's not a secret anymore!