Introduction
In this article i will explain about how constructor acts in the case of Inheritance.Description
As a developer we can saw constructor calling pretty easy and finds appropriate output according to our need using constructor. But in the case of Inheritance there is a different scenario of Constructor at the time of Object creation from derived class.While you using Inheritance with constructor you can find or write the following type of code for execution :-
using System;
class Parent
{
public Parent () {
Console.WriteLine("Hey Its
Parent.");
}
}
class Derived : Parent
{
public Derived () {
Console.WriteLine("Hey Its
Derived.");
}
}
class OrderOfExecution {
static void Main() {
Derived obj = new Derived();
}
}
The output from this program is shown here:
Hey Its Parent.
Hey Its Derived.
Oh Great! It prints Parent First means the Parent constructor call first but but but Constructor acts differently in Inheritance bit confusing for new Programmers. There are two concepts in execution of constructor
1. Calling
2. Execution
If you are Using Visual-Studio the you can see this using BreakPoint on this line :
Derived obj = new Derived();
and then press F11 and execute you program Line by Line then you can find it hits on Derived first and the Parent. The Reason behind this is following: -
When you create a object of your derived class Named Derived the constructor first goes to Derived() then it goes to Parent() because of its calling.
Constructor calling is done from Bottom to Top but then you find it Executes Parent() first then Derived() , that is because of its Execution.
Constructors Execution done from Top to Bottom. That's why it print Parent first then Base while base constructor called first.
0 comments:
Post a Comment