aspose file tools*
The moose likes Beginning Java and the fly likes constructors marked private Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "constructors marked private" Watch "constructors marked private" New topic
Author

constructors marked private

hari harann
Ranch Hand

Joined: Aug 07, 2008
Posts: 54
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 someone please explain the stuff given inside ( ). i really dont understand what they meant...
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38349
    
  23
A similar question came up a couple of days ago: here.
hari harann
Ranch Hand

Joined: Aug 07, 2008
Posts: 54
Thanks campbell, i have understood that. but my issue is the following sentence,

"the class must provide a static method or variable that allows access to an instance created from within the class"

please explain about the static method which they have mentioned here..
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38349
    
  23
That's a factory method. You call it something like getInstance.Note you can give different names to the factory methods; one here says it had the value 3 which comes from the no-args constructor.

Not a class anybody would use in real life, but it shows what you can do.
G Estes
Ranch Hand

Joined: Oct 22, 2002
Posts: 62
Or a singleton pattern where the static class gives out the one and only instance...
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11229
    
  16

if all the constructors are private, the only thing that can call those constructors are objects of that class, which won't exist until a constructor is called...

the work around is to create a static method that can be called without creating the object. that static method, since it is part of the class, can then call the constructor.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: constructors marked private