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
- using System;
- namespace Overridding {
- class Circle {
- public virtual double Area(double r) {
- return Math.PI * r * r;
- }
- }
- class Sphere: Circle {
- public override double Area(double r) {
- return 4 * base.Area(r);
- }
- }
- class Program {
- static void Main(string[] args) {
- Circle C = new Sphere();
- double area = C.Area(4);
- Console.WriteLine(area);
- }
- }
- }
Output
201.061929829747
Programming Example 2 - Using Abstract Keyword
- using System;
- namespace OverridingAbstract {
- abstract class Shape {
- public abstract double Area(double d);
- }
- class Circle: Shape {
- public override double Area(double r) {
- return (Math.PI * r * r);
- }
- }
- class Program {
- static void Main(string[] args) {
- Shape SC = new Circle();
- double area = SC.Area(5);
- Console.WriteLine(area);
- }
- }
- }
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!