Ad

Wednesday, August 14, 2013

Implement the Concept of Polymorphism Example in C#.Net?

Overview:
                In this article i would like to publish an article on Implement the Concept of Polymorphism Example in C#.Net.



Description:
                        Polymorphism is one of the concept of oops.Poly is a Greek word means "Many" Morphism means forms.It indicates the implementing a same concept with number of forms.
                       Polymorphism can be derived into two types.They are

  1. Static Polymorphism (or) Early Binding.
  2. Dynamic Polymorphism (or) Late Binding.
Static Polymorphism:
                              It is a process of linking a method with an object during compile time is called early binding.It is also called static polymorphism.In C#.Net static polymorphism can be divided into two types.They are
  1. Method Overloading
  2. Operator Overloading       
Method Overloading:
           It is a concept of providing a multiple definitions for a same method with in the same class.At the time of method overloading we must consider following conditions

  1. Name of the Method should be same
  2. Number of arguments and return type of arguments should differ
  3. No Need to bother about a return type of a method.
Example Demonstrates on Method Overloading:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Opl

{
    class Class1234
    {
        static void Main(string[] args)
        {
            mov o = new mov();
            o.prize(5000, "Class First Badge");
            o.prize("Class Second Badge");
            o.prize();
            Console.ReadLine();
        }
    }
    public class mov
    {
        public void prize(double m,string mom) //Two prameters
        {
            Console.WriteLine("For First Ranker {0} and cash prize {1}",m,mom);
        }
        public void prize(string p) //Single prameter
        {
            Console.WriteLine("For Second Ranker {0}",p);
        }
        public void prize()//No Parameters
        {
            Console.WriteLine("Congrats");
        }
    }
}

 Output:
Method Overloading
Operator Overloading:
In an object oriented programming language like C#, operator overloading provides a much more natural way of implementing the operations on custom types. Suppose that we have a class created for Complex number and we want to perform all the arithmetic operations on this type. One way to do this is by having functions like Add, Subtract inside the class and have the functionality. Another way is to actually have the overloaded version of operators to act on this type.

Operator overloading provides a much natural abstraction for the types. When we think about possible operation on some data type we can think of binary operators, unary operators, relational operators and perhaps some conversion operations to and from the basic types. In C# achieving all this is possible using operator overloading.

Points To Remember:

  • The operator function should be a member function of the containing type.
  • The operator function must be static.
  • The operator function must have the keyword operator followed by the operator to be overridden.
  • The arguments of the function are the operands.
  • The return value of the function is the result of the operation.
Syntax:
Acessspecifier static classname operator+(classname member1,classname member2....)
{
--------------------
}

E.G:
Public static op operator+(op a,op b)
{
--------------------
}
Program:
using System;

using System.Collections.Generic;

using System.Linq;
using System.Text;

namespace Opl
{
   public class Complex
   {
       public int real;
   public int imaginary;

   public Complex(int real, int imaginary)
   {
      this.real = real;
      this.imaginary = imaginary;
   }

   // Declare which operator to overload (+), the types
   // that can be added (two Complex objects), and the
   // return type (Complex):
   public static Complex operator +(Complex c1, Complex c2)
   {
      return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
   }
   // Override the ToString method to display an complex number in the suitable format:
   public override string ToString()
   {
      return(String.Format("{0} + {1}i", real, imaginary));
   }

   public static void Main()
   {
      Complex num1 = new Complex(2,3);
      Complex num2 = new Complex(3,4);

      // Add two Complex objects (num1 and num2) through the
      // overloaded plus operator:
      Complex sum = num1 + num2;

     // Print the numbers and the sum using the overriden ToString method:
      Console.WriteLine("First complex number:  {0}",num1);
      Console.WriteLine("Second complex number: {0}",num2);
      Console.WriteLine("The sum of the two numbers: {0}",sum);
      Console.ReadLine();

   }
   }
}

OutPut:
Opertaor OverLoading

















DynamicPloymorphism:



                             
  It is a process of linking a method with an object during runtime time is called late binding.It is also called dynamic polymorphism.In C#.Net dynamic polymorphism can be implemented with the concept of "Method Overriding".
                                                                               (or)
In this Mechanism by which a call to an overridden function is resolved at a Run-Time (not at Compile-time) if a base Class contains a method that is overridden. Method overriding means having two or more methods with the same name, same signature but with different implementation. In this process, an overridden method is called through the reference variable of a superclass, the determination of the method to be called is based on the object being referred to by reference variable.

Sample Program:


using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace movr1
{
    class Class10
    {
        static void Main(string[] args)
        {
            dehh o = new dehh();
            o.mm();
            Console.ReadLine();
        }
    }
    public class hh
    {
        public void mm()
        {
            Console.WriteLine("Base Class Method mm");
        }
    }
    public class dehh : hh
    {
        public void mm()
        {
            Console.WriteLine("Derived Class Method mm");
        }
    }
}

 Output:
Method Overriding1
Observation:
In the above program memory allocation will be at the run time for that particular method.So that second derived method functionality should be displayed.So that we can call it as runtime polymorphism.

What is Virtual Function: They implement the concept of polymorphism are the same as in C#, except that you use the override keyword with the virtual function implementation in the child class. The parent class uses the same virtual keyword. Every class that overrides the virtual method will use the override keyword.

Why to use them:

1)    It is not compulsory to mark the derived/child class function with Override KeyWord while base/parent class contains a virtual method

2)    Virtual methods allow subclasses to provide their own implementation of that method using the override keyword

3)    Virtual methods can’t be declared as private.

4)    You are not required to declare a method as virtual. But, if you don’t, and you derive from the class, and your derived class has a method by the same name and signature, you’ll get a warning that you are hiding a parent’s method

5)    A virtual property or method has an implementation in the base class, and can be overriden in the derived classes.

6)    We will get a warning if we won’t use Virtual/New keyword.

7)    Instead of Virtual we can use New Keyword

Program:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Factorial
{
    class Mov2123
    {
        static void Main(string[] args)
        {
            b o = new b();
            o.aa();
            o.hh();
            o.M();
            Console.ReadLine();
        }
    }
    public class a
    {
        public void M()
        {
            Console.WriteLine("Hi this is M Method");
        }
        public virtual void hh()
        {
            Console.WriteLine("This is hh Method");
        }
    }
    public class b : a
    {
        public void aa()
        {
            Console.WriteLine("This s a aa() method");
        }
        public override void hh()
        {
            Console.WriteLine("This is another hh() Method");
        }
        public new  void M()
        {
            Console.WriteLine("Hi.............");
        }
    }
}


Output:
Method Overriding2
Override Keyword: Method overriding is modifying or replacing the implementation of the parent class with a new one. Parent classes with virtual or abstract members allow derived classes to override them.

Program:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace mov3123
{
    class Class11
    {
        static void Main(string[] args)
        {
            p1 o = new p1();
            o.imp();
            Console.ReadLine();
        }
    }
    public class p
    {
        public virtual void imp()
        {
            Console.WriteLine("Designing a Page");
        }
    }
    public class p1 : p
    {
        public override void imp()
        {
            Console.WriteLine("Completed Page");
            Console.WriteLine("Thanks For Visiting My Blog.Keep Visiting");
        }
    }
}


Output:
Method Overiding 3





1 comment:

Unknown said...

Good explanation..i like your blog.Keep on going.