Method Hiding vs Method Overriding in C#?

Method Overriding is a language feature that allows a sub class  to provide a specific implementation of a method that is already provided by its super class. The implementation in the subclass overrides (replaces) the implementation in the superclass.

The important thing to remember about overriding is that the method that is doing the overriding is related to the method in the base class.

Method hiding, by contrast, does not have a relationship between the methods in the base class and derived class. The method in the derived class hides the method in the base class.

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
{
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 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:

Method Hiding:

In some situation we may want to have a method in the base class which can be implemented in the derived class independent of the method in the base class i.e we may want to have its new version altogether

In the following code i add a method Hello() in the base class and in the derived class give a completely new definition to the same method by preceding it with ‘new’ keyword

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class VirtualDemo
{
public virtual double Area(double r)
{
return r * r;
}
public void Hello()
{
Console.WriteLine(“Hello in Base Class”);
}
public class A : VirtualDemo
{
public override double Area(double r)
{
double p = 3.142;
return base.Area(r) * p;
}
public new void Hello()
{
Console.WriteLine(“Hello in Derived Class”);
}
}
public static void Main(string[] args)
{
A obj1 = new A();
Console.WriteLine(obj1.Area(3));
obj1.Hello();
Console.ReadLine();
}
}
}

Output:

28.278
Hello in Derived Class

 

Comments 1

Leave a Reply

Your email address will not be published. Required fields are marked *