Tuesday, 28 January 2014

Behavior of Constructors in Inheritance

Let us first create the inherited class.

public class myBaseClass
{
    public myBaseClass()
    {
        // Code for First Base class Constructor
    }

    public myBaseClass(int Age)
    {
        // Code for Second Base class Constructor
    }

    // Other class members goes here
}

public class myDerivedClass : myBaseClass
// Note that I am inheriting the class here.
{
    public myDerivedClass()
    {
        // Code for the First myDerivedClass Constructor.
    }

    public myDerivedClass(int Age):base(Age)
    {
        // Code for the Second myDerivedClass Constructor.
    }

    // Other class members goes here
}

Now, what will be the execution sequence here:
If I create the object of the derived class as:

myDerivedClass obj = new myDerivedClass()

Then the sequence of execution will be:
1.       public myBaseClass() method.
2.       and then public myDerivedClass() method.
Note: If we do not provide initializer referring to the base class constructor then it executes the no parameter constructor of the base class.
Note one thing here: we are not making any explicit call to the constructor of base class neither by initializer nor by the base keyword, but it is still executing. This is the normal behavior of the constructor.
If I create an object of the derived class as:

myDerivedClass obj = new myDerivedClass(15)

Then the sequence of execution will be:
1.       public myBaseClass(int Age) method
2.       and then public myDerivedClass(int Age) method
Here, the new keyword base has come into picture. This refers to the base class of the current class. So, here it refers to the myBaseClass. And base(10) refers to the call to myBaseClass(int Age) method.
Also note the usage of Age variable in the syntax: public myDerivedClass(int Age):base(Age). [Understanding it is left to the reader].

No comments:

Post a Comment