Thursday, March 24, 2016

Method Overriding Vs Method Hiding Using example in C#

Method Overriding & Method Hiding:


-  Method overriding / Hiding occurs when child class declares a method with the same name and 
    same Method Signature as parent class.

   In below example derived class has method (overrides method) print, which has same signature as 
   print method of Parent class  (BaseClass) 

- Base class method must be virtual or overridable

  Here in our example Base class method name Print() is virtual.

- Child Class Method must have override keyword before return type.  // Case 1: Method Overriding
   Here in our example child class method name Print() having override keyword before return type.

- Child Class Method must have New keyword before return type or no keywords before it.  // Case 2: Method Hiding
   Here in our example child class method name Print1() is New & in case of print2() method it has no keywords.
- Method overriding is also called as Run Time Polymorphism/ Dynamic Polymorphism/Late Binding.

Example of Method Overriding & Method Hinding.

using System;

namespace MethodOverriding_Hiding

    public class BaseClass
        public virtual void Print()
            Console.WriteLine("Base class method - Print");

        public virtual void Print1()
            Console.WriteLine("Base class method - Print1");

        public void Print2()
            Console.WriteLine("Base class method - Print2");

    public class DerivedClass : BaseClass
        public override void Print()
            Console.WriteLine("\n" + "Derived class method - Print"); // '/n' for new line.

        public new void Print1()
            Console.WriteLine("Derived class method - Print1");

        public void Print2()
            Console.WriteLine("Derived class method - Print2");

    class Program
        static void Main(string[] args)
            // Normal method - It will call respective class method only 
            // No matter of virtual/ override / New keyword
            BaseClass B = new BaseClass();

            DerivedClass D = new DerivedClass();

            //Method Overriding
            BaseClass B1 = new DerivedClass();
            // Base - virtual, Derived - Override -> Child Class (Overriden) method will be 
            // called & its Called as Method Overriding

            // Base - virtual, Derived - New or Void -> Base class (Hidden) will be called
            // & its Called as Method Hidding
// Base - void, Derived - void -> Base class (Hidden) will be called


Difference Between Method overriding vs. Method Hiding

  • In both cases parent and child class should have same method name and same signature
  • only difference is in case of Method overriding derived class should have overrides keyword
  • and in case of method hiding derived class should have New keyword.

When to use Method Overriding & Method Hiding using real time example

No comments:

Post a Comment