A special method of the class that will be automatically
invoked when an instance of the class is created is called as constructor.
A special method of the class that will be automatically
invoked when an instance of the class is created as constructor.
Constructors are mainly used to initialize private fields of
the class while creating an instance for the class.
Constructor can be classified into five types :
- Default Constructor
- Parameterized Constructor
- Copy Constructor
- Static Constructor
- Private Constructor
#1. Default Constructor :
When you are not creating a constructor in the class, then
compiler will automatically create a default constructor in the class that
initializes all numeric fields in the class to zero and all string and object
fields to null.
To create a constructor, create a method in the class with
same name as class and has the following syntax.
[Access Modifier] ClassName([Parameters])
{
}
Example program using constructor
using System;
class ProgramCall
{
int i, j;
//default constructor
public ProgramCall()
{
i = 45;
j = 76;
}
public static void main()
{
//When an object is created, constructor is called
ProgramCall obj = new ProgramCall();
Console.WriteLine(obj.i);
Console.WriteLine(obj.j);
Console.Read();
}
}
#2. Parameterized Constructor :
A constructor with at least one parameter is called as
parameterized constructor. Advantage of parameterized constructor is you can
initialize each instance of the class to different values.
Example for Parameterized Constructor
using System;
namespace ProgramCall
{
class Test1
{
//Private fields of class
int A, B;
//default Constructor
public Test1()
{
A = 10;
B = 20;
}
//Parameterized Constructor
public Test1(int X, int Y)
{
A = X;
B = Y;
}
//Method to print
public void Print()
{
Console.WriteLine("A = {0}\t B = {1}", A, B);
}
}
class MainClass
{
static void Main()
{
Test1 T1 = new Test1(); // default constructor is called
Test1 T2 = new Test1(80, 40); //Parameterized Constructor called
T1.Print();
T2.Print();
Console.Read();
}
}
}
#3. Copy Constructor
A parameterized constructor that contains a parameter of
same class type is called as copy constructor. Main purpose of copy constructor
is to initialize new instance to the values of an existing instance.
Example for Static Constructor
using System;
namespace ProgramCall
{
class Test2
{
int A, B;
public Test2(int X, int Y)
{
A = X;
B = Y;
}
//Copy Constructor
public Test2(Test2 T)
{
A = T.A;
B = T.B;
}
//Method to print
public void Print()
{
Console.WriteLine("A = {0}\t B = {1}", A, B);
}
}
class CopyConstructor
{
static void Main()
{
Test2 T2 = new Test1(80, 90);
//Invoking Copy Constructor
Test2 T3 = new Test1(T2);
T2.Print();
T3.Print();
Console.Read();
}
}
}
0 comments:
Post a Comment