• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

constructors marked private

 
hari harann
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48382
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A similar question came up a couple of days ago: here.
 
hari harann
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48382
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or a singleton pattern where the static class gives out the one and only instance...
 
fred rosenberger
lowercase baba
Bartender
Posts: 12084
29
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic