Polymorphism Part Two - Method Overriding In C#

In this article, I am going to explain the second type of polymorphism, i.e., Method Overriding. The first type of polymorphism, i.e., Method Overloading, is explained in the previous article.

Method Overriding means having multiple methods with the same signature, one method to be present in base class and the other in derived class. This can be achieved by using Virtual and Override keywords. Here, the same signature applies to:

  • Method Name
  • Method Return Type
  • Number of Parameters
  • Types of Parameters 

Method overloading is sometimes called Dynamic Polymorphism or Run Time Polymorphism or Late Binding. It means creating virtual methods in the base class and overriding the same method in a derived class. The overriding is used to modify the implementation of the base class. This implementation can be achieved by using either Abstract or Virtual keywords.

Programming Example 1 - Using Virtual Keyword
  1. using System;  
  2. namespace Overridding {  
  3.     class Circle {  
  4.         public virtual double Area(double r) {  
  5.             return Math.PI * r * r;  
  6.         }  
  7.     }  
  8.     class Sphere: Circle {  
  9.         public override double Area(double r) {  
  10.             return 4 * base.Area(r);  
  11.         }  
  12.     }  
  13.     class Program {  
  14.         static void Main(string[] args) {  
  15.             Circle C = new Sphere();  
  16.             double area = C.Area(4);  
  17.             Console.WriteLine(area);  
  18.         }  
  19.     }  
  20. }  
Output 

201.061929829747 

Programming Example 2 - Using Abstract Keyword 
  1. using System;  
  2. namespace OverridingAbstract {  
  3.     abstract class Shape {  
  4.         public abstract double Area(double d);  
  5.     }  
  6.     class Circle: Shape {  
  7.         public override double Area(double r) {  
  8.             return (Math.PI * r * r);  
  9.         }  
  10.     }  
  11.     class Program {  
  12.         static void Main(string[] args) {  
  13.             Shape SC = new Circle();  
  14.             double area = SC.Area(5);  
  15.             Console.WriteLine(area);  
  16.         }  
  17.     }  
  18. }   
Output

78.5398163397448
 
As we have seen in the above examples, method overriding is achieved by using both abstract and virtual keywords. Some key points to be remembered for implementing method overriding are:
  • The overridden method should always be declared as abstract, virtual or override in the base class.
  • The non-virtual & static method cannot be overridden.
  • Both virtual & override methods must have the same access level modifiers.
Conclusion

This article explained the concept of dynamic polymorphism using method overriding. I hope you enjoyed it :) .

If you have any queries, please comment.

Thanks!