Wednesday, 9 May 2012

Method Overriding


In some situations we want to have a class that has types(specially methods) that can possibly be modified in the derived class. In such situation we declare the method in the base class as virtual and precede the same method in the derived class with 'override' keyword
Consider the following code in which situation is that, a base class method Area() returns square of a parameter and suppose we want to extend this method in the derived class sothat this square may just be multiplied by a constant pi(3.142) so that it can return area of a circle:

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
      public class VirtualDemo
      {
            public virtual double Area(double r)
            {
               return r * r;
            }
      }
      public class A : VirtualDemo
      {
            public override double Area(double r)
            {
               double p = 3.142;
               return base.Area(r) * p;
            }
      }
      public class Test
      {
            public static void Main(string[] args)
            {
               A obj1 = new A();
               Console.WriteLine(obj1.Area(3));
               Console.ReadLine();
            }
      }
}
Output:
28.278
KeyPoints:
~virtual method must have its implementation in the base class and may optionally be overrided in the derived class if some additional functionality is required
~signature of the method in base as well as derived class should be the same
Now lets understand Method hiding by slightly modifying the same code:

No comments:

Post a Comment