Method overriding with detailed explanation


Definition: Method signature in base class as well as in derived class should be same.
 
If you are not satisfied with the implementation of a method in the parent class, you can keep the same declaration (signature and return type), but provide a different implementation.
 
Important Points:: 
  1. By using virtual and override keywords we can accomplish Method overriding.
  2. The virtual modifier indicates to derived classes that they can override this method.
  3. The override modifier allows a method to override the virtual method of its base class at run-time.
To achieve Run-time polymorphism or Late Binding, we are using Method Overriding concept.
 
Here, I am writing a simple program. 

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

namespace ConsoleApplication3
{
    class baseclass
    {
        public virtual int Add(int a, int b)
        {
            return a + b;
        }
    }
    class subclass : baseclass
    {
        public override int Add(int x, int y)
        {
            int d = 20;
            return base.Add(x,y)+d;
        }
    }
    class subclass2 : baseclass
    {
        public int Add(int x, int y)
        {
            int d = 40;
            return base.Add(x, y) + d;
        }
    }
    class something
    {
        public static void Main(String[] args)
        {
            baseclass baseclsinst = new baseclass();
            Console.WriteLine("Base class Addition::::::::::::" + baseclsinst.Add(23, 23));
            baseclass bscls = new subclass();
            Console.WriteLine("Derived class addition:::::::::" + bscls.Add(34, 54));
            baseclass bscls2 = new subclass2();
            Console.WriteLine("Derived class addition:::::::::" + bscls2.Add(34, 54));
            Console.ReadLine();
        }
    }
} 


Recommended Free Ebook
Similar Articles