CSDN博客

img waterboy

OOPS Corner : Instance Constructors

发表于2004/9/19 9:52:00  627人阅读

分类: WEBFORM


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.
0 0

相关博文

我的热门文章

img
取 消
img