vineri, 5 septembrie 2014

[C#] Private Constuctors

Private constructor are very important feature used extensively in Object oriented design and development. They are used when you don’t want to instantiate class and at the same time use its members. They are used when class only has static members.
Class Calculator
{
public static double e = 2.71828; 
private Calculator() {  }
public static int Add (int a,int b) {
 return a + b ;
}
Public static int Subtract (int a,int b) {
 Return a - b ;
}
Public static int Multiply(int a,int b) {
 return a * b ;
}
}
We cannot create objects of the “Calculator” as the constructor is private and even if we don’t specify access modifier it is treated as private.Such classes are used when you have lot of utility to be shared
in the application and don’t want to waste memory by creating objects every time you want to use such utility class.In that case you create all utility methods(or variables) as static members in class containing private constructor.

Niciun comentariu:

Trimiteți un comentariu