In this section, we will talk about practical implementation of Inheritance. Inheritance basically explains IS-A relationship. We will see the same in a moment. Below, I have created simple Doctor class which inherits from DoctorInfo.
Now, the 1st thing which I would like to do with this class is to create a constructor as shown below. But, for this I need to create one constructor in DoctorInfo class as well.Below is the implementation for the same.
Once, this is done, then our Doctor class with base class constructor will look like
Here, I have not called ToString() method explicitly as this is implemented in DoctorInfo and since writeLine method calls ToString(); Hence, it will automatically implement that method.
With this when I will run the program, then it will produce the following output.
Now, let us go ahead and create one method at both the places in Doctor and DoctorInfo as shown below.
Now, in the below screenshot, you will notice that compiler has raised one warning.
So, basically compiler is suggesting, if hiding is intended then use new keyword. Therefore, when we put new keyword before the same as shown below, then warning will not come.
And, this will work fine. But, under certain conditions, this won’t work.
This works fine as as DoctorInfo got populated with DoctorInfo and Doctor with Doctor. However, let us suppose the case.
Here, I am creating a variable of DoctorInfo but creating an object of Doctor. But, the problem with this approach is, when we invoke Information() method with this object, it will print different result.
Here, I was expecting Doctor Assigned message rather and that’s because of new keyword which hides the implementation. In order to overcome this scenario, we need to make use of virtual keyword. Virtual says that we expect this method to be overridden in derived class. Below is the minor change.
With the above change in place, and no change in main program. This will print the correct result.
Now, let’s verify the same against collection.
and, this will print the exact expected result.
I hope you would have enjoyed this segment. We will see more inn coming section. Till then stay tuned and Happy Coding. I have also shared the code in github. Download here:- https://github.com/rahulsahay19/csharp-Basics
1,753 total views, 1 views today