In this section we will see..
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 shouth bevel....................
EXAMPLE OF An Instance Constructor Is Given Below
Class myclass
{
Public myclass ()
{
Console.writeline ("I am Constructor");
}
}
Constructors Can Be overloaded That a Class Can Have SEVERAL CONSTRUCTORS with Each Construction 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.