Thursday, October 21, 2010

Inheritance

As we all know, inheritance is just the hierarchical relationship between various classes.
Class from which another class is inheriting some methods is base class and the other one is known as derived class.

For ex:
Class AA
{ }

Class BB : AA
{ }

Here, AA is your base class and B is your derived class.

Now a very basic question:
When we create an object of derived class, which constructor gets called?
1. Of Base Class
2. Of Derived Class
3. Both
4. None

Let's try to figure it with this example:

class AA
{
public AA()
{
Console.WriteLine("In AA");
}
}

class BB : AA
{
public BB()
{
Console.WriteLine("In BB");
}
}

class CC : BB
{
public CC()
{
Console.WriteLine("In CC");
}
}

Here, class CC is inheriting class BB and class BB is inheriting class AA.

class Program
{
static void Main(string[] args)
{
CC c = new CC();
}
}

I just created an object of CC in another class.
Now which constructor will be called?

Here is the output :


In case of inheritance, derived class always calls base class constructor first and then its own constructor.
Here, object of CC called the constructor of BB and similarly BB calls its base class constructor i.e., AA.
so, the sequence of execution is:
AA constructor -> BB constructor -> CC constructor


Bookmark and Share

No comments:

Post a Comment