Tuesday, 16 June 2015

Constructor and its types

Constructor

  1. It is a method of the class which automatically invoked when an instance of the class is created.
  2. Used for initializing private fields of the class while creating an instance for the class.
  3. If Constructor not created then compiler automatically create a default constructor in the class.
  4. Default constructor initializes all numeric fields in the class to zero and all string and object to null.
Key points of constructor are:
  1. A class can have any number of constructors.
  2. A constructor doesn't have any return type, not even void.
  3. A static constructor can not be a parametrized constructor.
  4. Within a class you can create only one static constructor. 
Types of Constructor are :
  1. Default constructor
  2. Parametrized constructor
  3. Copy Constructor
  4. Static Constructor
  5. Private constructor

Default Constructor

  1. Constructor without any parameters.
  2. Every instance of the class initialized to the same values.
  3. All numeric fields in the class initialized to zero.
  4. All string and objects fields initialized to null.
Example :

using System;
namespace
 DefaultConstractor
 {
    class addition
    {
        int a, b; 
        public addition()   //default contructor
        {
            a = 100;
            b = 175;
        }
        public static void Main()
        {
            addition obj = new addition(); //an object is created , constructor is called
            Console.WriteLine(obj.a);
            Console.WriteLine(obj.b);
            Console.Read();
        }
      }
    }

  Parametrized Constructor

  1. A Constructor with at least one parameter.
  2. We can initialize each instance of the class to different values.
Example:
using System;

namespace Constructor

{
    class paraconstrctor    {
      public  int a, b;
      public paraconstrctor(int x, int y)  // decalaring Paremetrized Constructor with passing x,y parameter

        {
            a = x;
            b = y;
        }
   }
    class MainClass
    {
        static void Main()
        {
            paraconstrctor v = new paraconstrctor(100, 175);   // Creating object of Parameterized Constructor and passing values 
            Console.WriteLine("-----------parameterized constructor example by vithal wadje---------------");
            Console.WriteLine("\t");
            Console.WriteLine("value of a=" + v.a );
            Console.WriteLine("value of b=" + v.b);
            Console.Read();
        }
    }
}

Copy Constructor

  1. This Constructor creates an object by copying variables from another object.
  2. Copy constructor  initializes 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. 

So let us see its practical implementation.
using System;

namespace copyConstractor

{
    class employee
    {
        private string name;
        private int age;
        public employee(employee emp)   // declaring Copy constructor.
        {
            name = emp.name;
            age = emp.age;
        }
        public employee(string name, int age)  // Instance constructor.
        {
            this.name = name;
            this.age = age;
        }
        public string Details     // Get deatils of employee
        {
            get
            {
                return  " The age of " + name +" is "+ age.ToString();
            }
        }
    }
    class empdetail
    {
        static void Main()
        {
            employee emp1 = new employee("Vithal", 23);  // Create a new employee object.

            employee emp2 = new employee(emp1);          // here is emp1 details is copied to emp2.

            Console.WriteLine(emp2.Details);
            Console.ReadLine();
        }
    }
}

Static Constructor

  1. A static constructor does not have parameters.
  2. A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  3. A static constructor cannot be called directly.
Syntax
class employee
 {// Static constructor
  static employee(){}
 }

Now let us see it with practically
using System;
namespace staticConstractor
{
public class employee
{
    static employee() // Static constructor declaration{Console.WriteLine("The static constructor ");
}
public static void Salary()
 {
    Console.WriteLine();
    Console.WriteLine("The Salary method");
 }
}
class details
{
    static void Main()
    {
        Console.WriteLine("----------Static constrctor example by vithal wadje------------------");
        Console.WriteLine();
        employee.Salary();
        Console.ReadLine();
    }
  }
}

Private Constructor

  1. When a constructor is created with a private specifier, it is not possible for other classes to drive from this class,neither is it possible to create an instance of this class.
  2. They are used in classes that contain static members only.
  3. We can create instance of this class by creating one public constructor.
  4. It provides an implementation of a singleton class pattern.
Example : 
using System;
namespace defaultConstractor
{
    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 example by vithal wadje----------");
            Console.WriteLine();
            Counter.currentview = 500;
            Counter.visitedCount();
            Console.WriteLine("Now the view count is: {0}", Counter.currentview);
            Console.ReadLine();
        }
    }
}














No comments:

Post a Comment