aspose file tools*
The moose likes Java in General and the fly likes Instantiating  a class with private constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
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: 24184
    
  34

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: 492

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://aspose.com/file-tools
 
subject: Instantiating a class with private constructor