In almost all interviews, interviewer had a
common question
If a Class A inherits B and B inherit C and if
I will create object of A or C then in what is order will constructor fire.
I had developed a simple mechanism for
clearing confusion on this so that at interview time we don't stress on this
question.
I had created hierarchy of a traditional
Indian family “Grandfather->Father->Son” and implement this on c#
So I had declare three classes :
Grandfather - Superior class
Father - Inherited by Grandfather.
Son - Inherited By father
namespace
InheritanceTest
{
class
InheritanceExample
{
static void
Main()
{
Son _son=new
Son();
Console.ReadLine();
}
}
class
GrandFather
{
public GrandFather()
{
Console.WriteLine("I
am Grandfather");
}
}
class Father
: GrandFather
{
public Father()
{
Console.WriteLine("I
am father");
}
}
class Son:Father
{
public Son()
{
Console.WriteLine("I
am Son");
}
}
}
So now when I create object of Son although it's object of son but due to our
social values we give highest regard to our grandfather and then to our father
and what remain is for son. So Output of this program is:
I am Grandfather
I am father
I am Son
So we can conclude that whenever we are
creating object of child class the first constructor will fire is the topmost
class (In our case Grandfather) in his hierarchy and so on(father-> Son)