Pages

Sunday, 14 June 2015

Constructor

Constructors

An instance constructor is a special method that is executed whenever a new instance of a class is created.
  • A constructor is used to initialize the state of the class instance.
  • If you want to be able to create instances of your class from outside the class, you need to declare the constructor public.
A constructor looks like the other methods in a class declaration, with the following exceptions:
  • The name of the constructor is the same as the name of the class.
  • A constructor cannot have a return value.
See following code fragment:
public class account
{ 
 private uint accoundID;     //field accountID
 private string accountFirstName;  //field accountFirstName
 private string accountLastName;   //field accountLastName
 private decimal accountBalance;   //field accountBalance

 public account(uint ID, string firstName, string LastName) //Class's Constructor
 {
  accoundID = ID;
  accountFirstName = firstName;
  accountLastName = LastName;
 }
 ....
}

Default Constructors

If no instance constructor is explicitly supplied in the class declaration, then the compiler supplies an implicit, default constructor, which has the following characteristics:
  • It takes no parameters.
  • It has an empty body.
If you declare any constructors for a class, then the compiler does not define the default constructor for the class.
public class myClass1   //myClass1 has no constructor, compiler will provide myClass1() as default constructor
{
 int myClass1Field;
}

public class myClass2   //myClass2 has  myClass2(int field) as constructor
{
 int myClass2Field;
 public myClass2(int field)
 {
  myClass2Field = field;
 }
}

class Program
{
 static void Main(string[] args)
 {
  myClass1 myObject1 = new myClass1();  //instantiate myClass1 using default constructor
  myClass2 myObject2 = new myClass2();  //error compile, myObject2 has no default constructor
  ...
 }
}

You can assign access modifiers to instance constructors just as you can to other members. You’ll also want to declare the constructors public so that you can create instances from outside the class. You can also create private constructors, which cannot be called from outside the class, but can be used from within the class.

0 comments:

Post a Comment