| Author |
private & protected constructors
|
Anilkumar Ravinuthala
Greenhorn
Joined: Jan 17, 2007
Posts: 17
|
|
|
please let me know the conditions we should prefer private & protected constructors
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32689
|
|
When you don't want the constructor called from outside their own class. When you don't want other classes to be able to instantiate this class. Example: the java.lang.Math class has a private constructor which makes it impossible to instantiate a Math object. Example: Go through these fora with the "search" option until you find "singleton." A "singleton" should only have one instance; its constructor is private so it can only be instantiated from inside its own class, so only one instance is ever created. A protected constructor only works when the superclass is hidden away in a different package. It then restricts constructor calls to classes in its own package (which you have hidden away) and its subclasses, presumably in the form "super(a, b, c);".
|
 |
 |
|
|
subject: private & protected constructors
|
|
|