Polymorphism / Inheritance in C# 2

Hello

Today we look into few more basic concepts of abstract class which continuation of my previous blog under C#.

We already declared a abstract class with abstract method and accessed it in derived classes and now we remove that abstract keyword from method allowing it to have simple method. This gives us compile error as show below:

noabstract

It means compiler asking us to implement the method but not to keep its signature only since it is does not have keyword as abstract or extern or partial. So let’s define the method in abstract class as shown below:

abstractclassnoabstractmathod

Now it is noted that Transformer is an abstract class but Run is not abstract hence it is implemented and neither abstract nor virtual key word is used in above. Let’s inherit this abstract class in Car, helicopter and boat classes and implement the same Run method as shown below:

nooverridecar

nooverrideheli

nooverrideboat

Please focus that derived classes does not have override keyword because abstract class run method does not have virtual keyword for which we receive output as Run From Abstract Transformer

output

The reason behind this behavior is that always parent Run method is called because it is not allowing to gets executed of child Run method. This can be avoided if we use virtual keyword in abstract class and override keyword in child classes. With this parent Run method can be bypassed and child Run method gets executed if have override keyword else virtual Run method will be executed as shown below:

virtualtransformer

As you can see that parent abstract class have Run method with virtual keyword and respective child classes must have override keyword.

virtualcar

virtualboat

virtualheli

Now the output of the following program is as :

outputvirtualoverride

That’s all for the day.

Happy Programming.. 🙂

 

Leave a comment