OOPS Corner : Instance Constructors

来源:互联网 发布:女神联盟星灵进阶数据 编辑:程序博客网 时间:2024/05/16 11:26

In this section we will see about instance constructors.

Instance Constructors

Instance constructors are responsible for setting an object instance to its initial state. Instance constructors of classes are invoked whenever an instance of a class is created.

Syntax of a simple instance constructor is as follows

ConstructorName()
{
...constructor body
}

Note that the name of the constructor should be same as that of the class and constructors cannot return any value not even void. Failing these conditions will result in a compiler error.

Example of an Instance Constructor is given below

class MyClass
{
public MyClass()
{
Console.WriteLine(“I am Constructor”);
}
}

Constructors can be overloaded meaning that a class can have several constructors with each constructor taking a different set of parameters as shown in sample below

class MyClass
{
public MyClass()
{
Console.WriteLine("No Parameter");
}

public MyClass(string param1)
{
Console.WriteLine("One Parameter");
}

public MyClass(string param1, int param2)
{
Console.WriteLine("Two Parameters");
}
}

If a class does not contain any instance constructor, a default parameter less instance constructor will be provided automatically. This default constructor will initialize the object fields to their default values.

Variable initializers are executed automatically before constructor body for example

class MyClass
{
int x=5;
int y;
public MyClass()
{
Console.WriteLine("X={0},Y={1}",x,y);
}
}

class startUP
{

publicstaticvoid Main()
{
MyClass MC=new MyClass();
}
}

will result in X=5,Y=0 as x is initialized to 5 and y is initialized to the default value of 0.
原创粉丝点击