Blog

Polymorphism with example

Posted by Amit Patel Blogs | C# Language Jun 04, 2012
This blog talks about polymorphism with an example using C#.

Introduction

What is Polymorphism?

Polymorphism means same operation may behave differently on different classes.

  • Example of Compile Time Polymorphism: Method Overloading
  • Example of Run Time Polymorphism: Method Overriding

Example of Compile Time Polymorphism

  • Method Overloading: Method with same name but with different arguments is called method overloading.
  • Method Overloading forms compile-time polymorphism.

Example of Method Overloading:

class A1
{
     void hello()
     {
         Console.WriteLine("Hello");
     }
     void hello(string s)
     {
         Console.WriteLine("Hello {0}",s);
     }
}

Example of Run Time Polymorphism

  • Method Overriding: Method overriding occurs when child class declares a method that has the same type arguments as a method declared by one of its superclass.
  • Method overriding forms Run-time polymorphism.


Note: By default functions are not virtual in C# and so you need to write “virtual” explicitly. While by default in Java each function are virtual.
Example of Method Overriding:

Class parent
{
   virtual void hello()
   {
      Console.WriteLine("A D Patel");
   }
}
Class child : parent
{
   override void hello()
   {
      Console.WriteLine("R A Patel");
   }
}
static void main()
{
   parent objParent = new child();
   objParent.hello();
}
//Output
R A Patel

COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Get Career Advice from Experts
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Join a Chapter