Pages

Sunday, 28 June 2015

Constructor Execution

Constructor Execution

Lets take a look at our code below:
class person
{
 public string firstName;
 public string lastName;
 public ushort age;
 public person()
 {
  Console.WriteLine("person constructor Called");
 }
 public void greet()
 {
  Console.WriteLine("Hello "+ firstName + " " + lastName);
 }
 
 public void talk(string words)
 {
  Console.WriteLine(firstName+" "+ lastName + " say "+ words);
 }
}

class employee : person
{
 public string company;

 public employee()
 {
  Console.WriteLine("employee constructor Called");
 }
 
 new public void greet()
 {
  Console.WriteLine("Hello " + firstName + " " + lastName);
  Console.WriteLine("I work for " + company);
 }
}
class Program
{
 static void Main(string[] args)
 {
  employee me=null;

  me = new employee();
  me.firstName =  "Yang";
  me.lastName = "Sopiana";
  me.company = "Company.inc";
  me.age = 29;
  me.greet();
 }
}

The code will display following output:
person constructor Called
employee constructor Called
Hello Yang Sopiana
I work for Company.inc

From the output we can can know that when an instance is being created, one of the first things that’s done is the initialization of all the instance members of the object. After that, the base class constructor is called. Only then is the body of the constructor of the class itself executed.

0 comments:

Post a Comment