Polymorphism, method overloading and overriding in C#

Goud.Kv
Posted by in C# category on for Beginner level | Points: 250 | Views : 83623 red flag
Rating: 5 out of 5  
 1 vote(s)

C# is an Object-oriented programming language. C# comes with simplicity, expressiveness and great performance to meet the programmer productivity.
Recommendation
Read implicit, explicit and operator keywords in C# before this article.

Introduction

So far, we have seen conversion keywords in C#. Now, let's study polymorphism, static and dynamic polymorphism in C# in this chapter.

Objective

The main objective of this article is to learn about method overloading and method overriding in polymorphism in C# programming.

Polymorphism

Polymorphism simply means 'many forms'. After encapsulation and inheritance, polymorphism plays a major role in object-oriented programming.
In other words, polymorphism means the states or behaviors of an object such as emotions of a person.

There are two types of polymorphism. They are,

Above diagram shows the brief architecture of polymorphism in object-oriented programming.

Static Polymorphism

In static polymorphism, the decision and response to a method is determined at the compile time. Therefore, it is also known as compile-time polymorphism. Static polymorphism involves static binding or early binding.

As the name indicates that early binding links a method with an object at compile time. Hence, calling of method should be done in compile time only.

Method overloading and operator overloading are the examples of static polymorphism.

Method Overloading:
Method overloading or function overloading is the concept of having more than one methods in a class with the same name and different parameters.

Compiler automatically calls required method by checking number of parameters and their type which are passed into that method.

If the credentials (number of parameters and type) doesn't matched by any method signatures, then it will give compile time error.

Example,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Man
{
    class MyClass
    {
        public void MyMethod(int x, int y)              // MyMethod with int parameters
        {
            Console.WriteLine("Integers = " + x + y);
        }
        public void MyMethod(char x, char y)            // MyMethod with char parameters
        {
            Console.WriteLine("Characters = " + x + y);
        }
        public void MyMethod(string x, string y)        // MyMethod with string parameters
        {
            Console.WriteLine("Strings = " + x + y);
        }
    }

    class Program
    {
        static void Main()
        {
            MyClass var = new MyClass();
            var.MyMethod(2, 3);                      // This automatically calls int's method
            var.MyMethod('a', 'b');                  // This calls char's method
            var.MyMethod("Method", "Overloading");   // This automatically calls string's method
        }
    }
}
In the above example code, we have three functions with the same name (MyMethod) but different parameters i.e. int parameters for the first one, chars for the second and strings for the third one. 

In the Main method, if we instantiate integer values, it automatically goes and calls a method which has int parameters.

And if we give characters, it automatically invokes the method which has char parameters. 

Similarly if we instantiate string items, it calls the particular method (MyMethod with string parameters) in that class.

Output of this program will prints the following lines in your console,


Dynamic Polymorphism

In dynamic polymorphism, the decision and response to a method is determined at the run time. Therefore, it is also known as run-time polymorphism. dynamic polymorphism involves late binding.

late binding or dynamic binding is a process of linking method to an object during run time (run-time binding).

Method overriding is an example of dynamic polymorphism.

Method Overriding:
Method overriding or function overriding is the concept of having duplicated methods in base and derived classes with same name as well as same parameters.
  • Only abstract and virtual methods can be overridden.
  • We cannot declare an abstract method without an abstract class.
  • And we cannot an instance of an abstract class.
  • For more information, read abstract and virtual modifiers.
Because of run-time binding, we can point to any derived class from the base class object at the run time.

Compiler doesn't participate in here to check whether the method is available or not for overriding functionality. Hence, it doesn't throws any compile time errors at in this case. 

All the decisions are made at the runtime and we will get runtime error if there is no method to be called.

Example,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Man
{
    class BaseClass
    {
        public virtual void MyMethod()   // Virtual method; Gives runtime error if you remove this method
        {
            Console.WriteLine("This is the Base Class");
        }
    }

    class DerivedClass : BaseClass
    {
        public override void MyMethod()  // Overriding virtual method 
        {
            Console.WriteLine("This is the Derived Class");
        }
    }

    class Program
    {
        static void Main()
        {
            BaseClass msg = new BaseClass();
            msg.MyMethod();                    // This will call the BaseClass method

            msg = new DerivedClass();
            msg.MyMethod();                    // This will call the DerivedClass method
        }
    }
}
In the above example, we have a virtual method MyMethod() in the BaseClass which is overridden in the DerivedClass.

In the Main method, we created an object which is initially pointed to BaseClass method. Hence it calls that method at the runtime
Again we pointed the same object to the DerivedClass method in which it calls that method at the runtime.

Output of the above code will prints the following lines in your console,


Now in the above code, remove the MyMethod() in the BaseClass and run again. 

This will throw a runtime error like below,


Conclusion

In this article, we have studied about polymorphism and types of polymorphism with examples. Hope you understand.

Thanks for reading.

Regards,
Krishna.

Recommendation
Read Struct, properties of structs in C# after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Goud.Kv
Full Name: Krishna Vamshi Goud
Member Level: Gold
Member Status: Member,MVP
Member Since: 2/12/2014 2:34:09 AM
Country: India
Thanks & Regards, Krishna


Login to vote for this post.

Comments or Responses

Posted by: Mamireddy on: 9/17/2014 | Points: 25
Hello Vamshi you have posted Good articles with examples for beginers as well as experience peoples also refresh the subject.... Keep it up.....

thank you,
MallaReddy
Posted by: Goud.Kv on: 9/18/2014 | Points: 25
Thanks for your appreciation...

Regards,
Krishna.

Login to post response

Comment using Facebook(Author doesn't get notification)