| 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
|
|
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
|
 |
 |
|
|
subject: Instantiating a class with private constructor
|
|
|