Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Instantiating a class with private constructor

 
ragi singh
Ranch Hand
Posts: 198
Oracle Suse
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,

I am preparing for SCJP and was reading rules for constructors however , there is an extract in the book about classes with private constructors which is as follows:-

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 anyone explain with a relevant example how are we going to instantiate this class with private constructor ?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use the one Example object in the public static variable INSTANCE, but you can't create any more:

 
ragi singh
Ranch Hand
Posts: 198
Oracle Suse
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok thank you i got the point .
 
Hunter McMillen
Ranch Hand
Posts: 492
Firefox Browser Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
look up the singleton pattern for a real world use of what you're talking about.
Singleton Pattern

Ex:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic