Wednesday, June 4, 2014

Constructors and there types


Constructor
A special method of the class that will be automatically invoked when an instance of the class is created is called a constructor. 
When you have not created a constructor in the class, the compiler will automatically create a default constructor in the class. The default constructor initializes all numeric fields in the class to zero and all string and object fields to null. 

Some of the key points regarding the Constructor are:
  • A class can have any number of constructors.
  • A constructor doesn't have any return type, not even void.
  • A static constructor cannot be a parameterized constructor.
  • Within a class you can create only one static constructor

Types of Constructor
Default Constructor
A constructor without having any parameters called default constructor. In this constructor every instance of the class will be initialized without any parameters.
This can be defined by a programmer or compiler will define when no constructor defined under the class.

The drawbacks of default constructor are that every instance of the class will be initialized to the same values and it is not possible to initialize each instance of the class to different values.
Example 1
public class Class1
    {
int roll; float marks;
public Class1() //constructor
        {
roll = 6;
marks = 0.6f;
Console.WriteLine(roll);
Console.WriteLine(marks);
        }
    }

class Program
    {
static void Main(string[] args)
        {
            Class1 obj = new Class1();   // Once object of class created automatically constructor will be called

Console.ReadLine();
        }
    }

Output:






Example 2
namespace ConsoleApplication1
{
class addition
    {
int a, b;
public addition()  
        {
            a = 111;
            b = 125;
        }

public static void Main()
        {
additionobj = new addition();
Console.WriteLine(obj.a);
Console.WriteLine(obj.b);
Console.Read();
        }
    }
}



Example 3
class c1
    {
inta,b;
public c1()
        {
this.a=10;
this.b=20;
        }
public void display()
        {
Console.WriteLine(" value of a:{0}",a);
Console.WriteLine(" value of b: {0}",b);
        }
    }
class Program
    {
static void Main(String[] args)
        {
c1obj = new c1();
obj.display();
Console.ReadLine();
        }
    }
Output:





Parametrized Constructor
A constructor with at least one parameter is called a parameterized constructor. The advantage of a parametrizedconstructor is that you can initialize each instance of the class to different values.



classparameterconstructor
    {
publicint a, b;
publicparameterconstructor(int x, int y)
        {
            a = x;
            b = y;
        }
    }
classProgram
    {
staticvoid Main(string[] args)
        {
parameterconstructorobj = newparameterconstructor(100, 175);
Console.WriteLine("a " + obj.a);
Console.WriteLine("b " + obj.b);
Console.Read();
        }
    }

Output:


classparameterconstructor
    {
publicint a, b;
publicparameterconstructor(int x, int y)
        {
            a = x;
            b = y;
        }

publicvoid Display()
        {
Console.WriteLine("value of a  {0}", a);
Console.WriteLine("value of b {0}", b);

        }
    }
classProgram
    {
staticvoid Main(string[] args)
        {
parameterconstructorobj = newparameterconstructor(100, 175);
obj.Display();
Console.Read();
        }
    }

Output



Constructor Overloading

In C# it possible to overload the constructors, it means we can have more than one constructor with different parameters

classSample
        {
publicstring param1, param2;

public Sample()     // Default Constructor
            {
            param1 = "Hi";
            param2 = "I am Default Constructor";
            }
public Sample(string x, string y)     // Declaring Parameterized constructor with Parameters
            {
            param1 = x;
            param2 = y;
            }
        }
classProgram
          {
staticvoid Main(string[] args)
              {
Sampleobj = newSample();   // Default Constructor will Called
Sample obj1 = newSample("Welcome", "uday");   // Parameterized Constructor will Called
Console.WriteLine(obj.param1 + ", " + obj.param2);
Console.WriteLine(obj1.param1 + " to " + obj1.param2);
Console.ReadLine();
              }

          }


Output:






Copy constructor
The constructor which creates an object by copying variables from another object is called a copy constructor. The purpose of a copy constructor is to initialize a new instance to the values of an existing instance.
Syntax
public employee(employee emp)
{
name=emp.name;
age=emp.age;
}

The copy constructor is invoked by instantiating an object of type employee and passing it the object to be copied.

Example
employee emp1=new  employee (emp2);
Now, emp1 is a copy of emp2. 



classSample
    {
publicstring param1, param2;
public Sample(string x, string y)
        {
            param1 = x;
            param2 = y;
        }
public Sample(Sampleobj)     // Copy Constructor
        {
            param1 = obj.param1;
            param2 = obj.param2;
        }
    }
classProgram
    {
staticvoid Main(string[] args)
        {
Sampleobj = newSample("Welcome", "uday");  // Create instance to class Sample
Sample obj1 = newSample(obj); // Here obj details will copied to obj1
Console.WriteLine(obj1.param1 + " to " + obj1.param2);
Console.ReadLine();
        }
    }

Output
class employee
    {
        private stringname;
        private intage;
        publicemployee(employee emp)   // declaring Copy constructor.
        {
            name = emp.name;
            age = emp.age;
        }
        publicemployee(string name, intage)  // Instance constructor.
        {
            this.name = name;
            this.age = age;
        }
        public stringDetails     // Get deatils of employee
        {
            get
            {
                return " The age of " + name + " is " + age.ToString();
            }
        }
    }
    class empdetail
    {
        static voidMain()
        {
            employeeemp1 = new employee("dsaf", 23);  // Create a new employee object.
            employeeemp2 = new employee(emp1);          // here is emp1 details is copied to emp2.
            Console.WriteLine(emp2.Details);
            Console.ReadLine();
        }
    }

 Output:



Static constructor
When we declared constructor as static it will be invoked only once for any number of instances of the class and it’s during the creation of first instance of the class or the first reference to a static member in the class. Static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.

Importance points of static constructor

There should be no parameter(s) in static constructor.
Reason: Since, It is going to be called by CLR, nobody can pass the parameter to it

-      Static constructor will not have any access modifiers.
1.  There should be no access modifier to it.
Reason: Again the reason is same call to static constructor is made by CLR and not by the object, no need to have access modifier to it

-   Static constructor will execute automatically whenever we create first instance of class
-      Only one static constructor will allowed.

1.  A static constructor cannot be called directly.

using System;  
public Class question {
 static question()
 {
//initialize static member only.
  }
  public question()
  {
// codes for the first derive class constructor.  }
 }

Ans : Yes, this is perfectly valid even if it doesn't match with the rule of overloading concept. The only reason of being it valid is that the time of execution of the two constructors are different, (i) static question() at the time of loading the assembly and (ii) public question() at the time of creating object.


Static constructors are introduced with C# to initialize the static data of a class. CLR calls the static constructor before the first instance is created.

The static constructor has the following features:
  • No access specifier is required to define it.
  • You cannot pass parameters in static constructor.
  • A class can have only one static constructor.
  • It can access only static members of the class.
  • It is invoked only once, when the program execution begins.



class Sample
    {
        public stringparam1, param2;
        staticSample()
        {
            Console.WriteLine("Static Constructor");
        }
        publicSample()
        {
            param1 = "Sample";
            param2 = "Instance Constructor";
        }
    }
    class Program
    {
        static voidMain(string[] args)
        {
            // Here Both Static and instance constructors are invoked for first instance
            Sampleobj = new Sample();
            Console.WriteLine(obj.param1 + " " + obj.param2);
            // Here only instance constructor will be invoked
            Sampleobj1 = new Sample();
            Console.WriteLine(obj1.param1 + " " + obj1.param2);
            Console.ReadLine();
        }
    }






class Sample
    {
       
        staticSample()
        {
            Console.WriteLine("Static Constructor");
        }
        public static voidSalary()
        {
            Console.WriteLine();
            Console.WriteLine("The Salary method");
        }
    }
    class Program
    {
        static voidMain(string[] args)
        {
            // Here Both Static and instance constructors are invoked for first instance
            Sampleobj = new Sample();
            Sample.Salary();
            Console.ReadLine();
        }
    }

Output




What is use of static constructor in real time


Static constructor is used to initialize static data members as soon as the class is referenced first time. Through this we can restrict creating multiple objects for a class.

Singleton pattern is the best example for this. As you know each object occupies some space in memory. But by this method we can reduce it. That means increase in perfomance.


Private Constructor
When a constructor is created with a private specifier, it is not possible for other classes to derive from this class, 
neither is it possible to create an instance of this class. They are usually used in classes that contain static members
only.

The main purpose of creating private constructor is used to restrict the class from being instantiated when it contains every member as static.
Once we provide a constructor that is either private or public or any, the compiler will not allow us to add public constructor without parameters to the class.

1.  One use of a private constructor is when we have only static members.
2.  It provides an implementation of a singleton class pattern
3.  Once we provide a constructor that is either private or public or any, the compiler will not add theparameter-less public constructor to the class.



They are usually used in classes that contain static members only.

public class Sample
    {
        public string param1, param2;
        public Sample(string a, string b)
        {
            param1 = a;
            param2 = b;
        }

      
        private Sample()  // Private Constructor Declaration
        {
            Console.WriteLine("Private Constructor with no prameters");
        }
    }
    class Program
    {
        static void Main(string[] args)
       
        {
         
            // Here we don't have chance to create instace for private constructor
            Sample obj = new Sample("Welcome", "to sadf-safd");
            Console.WriteLine(obj.param1 + " " + obj.param2);
            Console.ReadLine();
        }
    }



Output:




using System;
 public Class demo {
  private demo()
 {
  Console.WriteLine("This is no parameter private constructor");
 }
 public demo(int a):this()
{
 Console.WriteLine("This is one parameter public constructor");
  }
 // other methods
}
   
The object of the class can be created as :
demo obj = new demo(10) ; //it will work fine.

  demo obj = new demo() ; // error of inaccessibility will be occur.



Example

public class Counter
    {
        private Counter()   //private constrctor declaration
        {
        }
        public static int currentview;
        public static int visitedCount()
        {
            return ++currentview;
        }
    }
    class viewCountedetails
    {
        static void Main()
        {
            // Counter aCounter = new Counter();   // Error
            Console.WriteLine("-------Private constructor ----------");
            Console.WriteLine();
            Counter.currentview = 500;
            Counter.visitedCount();
            Console.WriteLine("Now the view count is: {0}", Counter.currentview);
            Console.ReadLine();
        }
    }


Output:




A variable declared under the class is a Class Variable and accessible through out the class, where as variables declared under a block are block variables and accessible only with in the block.

-If a class and block variable are declared with the same name, with in the block the preference goes to block variables only, in such cases to refer to the class variables from that blocks use the "this" keyword.

-"this" is used for referring to the members of a class like variables or methods.

-To test this change the constructor code in the previous program as following:
       Params(int x , int y)  
              {
                   this.x = x;
                      this.y = y;

              }


Inheritance based overloading

 If a method is overloaded under a child class  we called it as inheritance based overloading
Public void Test()   -- load parent
Public void Test(int x)—load parent


Public void Test(String s)- load child

















Instance Constructor Vs Static constructor
A constructor declared using static modifier is a static constructor, rest all instance constructors.

Static constructor responsible for initializing static variables and instance constructor responsible for initializing instance variables.

A static constructor gets called one and only once in the execution of a class. i.e when the class execution starts.
Where as  instance constructor gets called zero or n Times  i.e each time the object of the class get created.
The first block of code which get executed in a class, is static constructor.


As we can pass parameters to an instance constructor, it can’t be done in the case of static constructor ,because a static constructor never takes parameters or can’t be parameterized

Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...