Method overriding in C sharp

  • Method overriding is a feature that allows you to invoke functions (that have the same signatures) that belong to different classes in the same hierarchy of inheritance using the base class reference.
  • In other words, it is a concept of having same prototypes (i.e., same function name and same arguments) in the base class and derived class.
  • In order to access parent class methods (or fields), base keyword is used.
  • C# makes use of two keywords: virtual and overrides to accomplish method overriding.
    • Method of the base class must be marked as virtual.
    • Method of derived class must be declared as override.
  • For e.g.,
  • using System;
    
    namespace OverrideDemo
    {
        class BC 
        {
            public virtual int prod(int a, int b)
            {
                return a * b;
            }
        }
    
        class DC1 : BC
        {
            public override int prod(int x, int y)
            {
                int d = 10;
                return base.prod (x, y) * d;
            }
        }
        class DC2 : BC
        {
            public override int prod(int x, int y)
            {
                int d = 20;
                return base.prod(x, y) * d;
            }
        }
        class Demo
        {
            static void Main(string[] args)
            {
                BC obj = new BC();
                Console.WriteLine("From Base class: " + obj.prod(3, 4));
                BC obj1 = new DC1();
                Console.WriteLine("From Derived class 1: " + obj1.prod(3, 4));
                BC obj2 = new DC2();
                Console.WriteLine("From Derived class 2: " + obj2.prod(3, 4)); 
                Console.ReadLine();
            }
        }
    }
Note:
  • 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
  • If any class method doesn't have 'virtual', 'abstract' or 'override' keyword and we attempt to have its new implementation in any derived class a warning is generated to supply 'new' keyword to the method in the derived class.We can also not override that class method unless that method has 'virtual' keyword
Question: Can you override private virtual methods?
Answer: No. You cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.

0 comments :

Post a Comment

> Related Posts with Thumbnails
 

Copyright © 2012. GS dot net - All Rights Reserved - Design by BTDesigner - Proudly powered by Blogger