Wednesday, April 11, 2007

Private constructor

What is a Private constructor . Why is a constructor made private.. This private, public and protected access modifiers are used always for two things..
1) To confuse u ;)
2) To allow and deny access to other classes.(As the name)
Private constructors prevent a class from being explicitly instantiated by callers.

I know the next question , When do u want the callers not to instantiate the class.

Whenever a class contains
* only static utility methods
* contains only constants
* type safe enumerations
* singletons
u can make their constructors private...

If the programmer does not provide a constructor for a class, then the system will always provide a default, no-argument constructor. To disable this default constructor, simply add a private constructor to the class. This private constructor can be empty.

Example of a class containing constants

public final class Consts {

* Prevent object construction outside of this class.
private Consts(){

public static final String NEW_LINE = "\n";
public static final String EMPTY_STRING = "";
public static final String SPACE = " ";
public static final String PERIOD = ".";
public static final String TAB = "\t";

//algebraic signs
public static final int POSITIVE = 1;
public static final int NEGATIVE = -1;
public static final String PLUS_SIGN = "+";
public static final String NEGATIVE_SIGN = "-";

the Consts class declared contains only static and final constants . When we have all static values in a class and their values cannot be changed why do you want to instantiate an object for it. We create objects for a class to hold different values of the variable defined in the class. So as the variables are final,w cant modify them and since they are static the same memory space will be used for all the objects instantiated so why should we instantiate for such type classes.

No comments: