Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
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 REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Private Constructor" Watch "Private Constructor" New topic

Private Constructor

Vivek Alampally
Ranch Hand

Joined: Jul 10, 2008
Posts: 67
Kindly explain me, what exactly author is trying to explain with example in the following paragraph
"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.)"

Siddhesh Deodhar
Ranch Hand

Joined: Mar 05, 2009
Posts: 118
Have a look at this Link

Good, Better, Best, Don't take rest until, Good becomes Better, and Better becomes Best.
Sidd : (SCJP 6 [90%] )
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

constructor is a special kind of method , you can specify an access specifier[what are all applicable to a method] to a constructor. so you can not access the *particular* constructor of that class[say class A] from other class[say class A]. and if you want to instantiate A from B then, provide a public method[Factory method] in A which create an object of A[private scope is available inside a class], and access the method from class B. this technique is useful in some core design pattern like singleton pattern, strategy pattern etc...

Darryl Burke

Joined: May 03, 2008
Posts: 5091

Seetharaman Venkatasamy wrote:constructor is a special kind of method

No it isn't. A constructor is most emphatically NOT a method.

luck, db
There are no new questions, but there may be new answers.
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Darryl Burke wrote:A constructor is most emphatically NOT a method.

Yes, you are right; that is why I mentioned as *special kind* of method
Rob Spoor

Joined: Oct 27, 2005
Posts: 20183

But that implies constructors are methods, which they aren't.

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: Private Constructor
It's not a secret anymore!