Difference Between Method Hiding & Method Overriding

Difference Between Method Hiding & Method Overriding
Difference Between Method Hiding & Method Overriding

We have seen how Method Hiding & Method Overriding works.  It is time know the main difference between them.  This will give you the idea when and where to use them.

Method Hiding:  In method hiding, if both derived class and base class has a same method name with same signature, then we make use of new keyword to hide the base class method.  But if we create a base class reference variable pointing to the derived class object, then base class method will be called.

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

namespace Hello
{
    class Student
    {
        public void PrintName()
        {
            Console.WriteLine("Method from Base Class");
        }
    }

    class Student1 : Student
    {      

       public new void PrintName()
       {
           Console.WriteLine("Method from Derived Class");
       }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Student S1 = new Student1();
            S1.PrintName();
        }
    }
}

 Output:

Method from Base Class
Press any key to continue . . .

Method Overriding:  In method overriding, if both derived class and base class has a same method name with same signature, then we mark base class method as virtual using virtual keyword, so that it can be overridden by all the derived classes.  In this case, if we create a base class reference variable pointing to the derived class object, then derived class method will be called.

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

namespace Hello
{
    class Student
    {
        //marked virtual
        public virtual void PrintName()
        {
            Console.WriteLine("Method from Base Class");
        }
    }

    class Student1 : Student
    {   
        //overriden
        public override void PrintName()
       {
           Console.WriteLine("Method from Derived Class");
       }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //base class reference variable pointing to derived class object.
            Student S1 = new Student1();
            S1.PrintName();
        }
    }
}

 Output:

Method from Derived Class
Press any key to continue . . .

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •