It's not a secret anymore!
The moose likes Java in General and the fly likes Instantiating  a class with private constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Instantiating  a class with private constructor" Watch "Instantiating  a class with private constructor" New topic
Author

Instantiating a class with private constructor

ragi singh
Ranch Hand

Joined: Mar 10, 2010
Posts: 198

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

Joined: Jul 08, 2003
Posts: 24056
    
  13

You can use the one Example object in the public static variable INSTANCE, but you can't create any more:



[Jess in Action][AskingGoodQuestions]
ragi singh
Ranch Hand

Joined: Mar 10, 2010
Posts: 198

ok thank you i got the point .
Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 490

look up the singleton pattern for a real world use of what you're talking about.
Singleton Pattern

Ex:


"If the facts don't fit the theory, get new facts" --Albert Einstein
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Instantiating a class with private constructor
 
Similar Threads
Constructor Rules
private constructor
Construtor rules
Is it possible for a class to have a private constuctor???
constructor doubt