Definition of Overrtide for Beginners with the help of a example.
Introduction
If a new developer add one new method in child class but unfortunately that same method present in parent class also. These situations are called method hiding.
Sample:
class Home
{
public void Fan()
{
Console.WriteLine("Home--->Fan");
}
}
class Hotel:Home
{
public void Fan()
{
Console.WriteLine("Hotel--->Fan");
}
}
class Building
{
static void Main(string[] args)
{
Home objhome = new Home();
Hotel objhotel = new Hotel();
objhome.Fan();
objhotel.Fan();
}
}
In the above sample class home as well as class hotel having the same method called fan(). Then in main, I created separate objects for those
classes and called their individual methods. yup its working fine but its working with one warning what’s that.
Result:
Home---->Fan
Hotel--->Fan
Warning :
‘MethodHiding.Hotel.Fan ()' hides inherited member ‘MethodHiding.Home.Fan ()'. Use the new keyword if hiding was intended.
By seeing the warning itself we identify the hotel class fan method hiding the home class fan method. What to-do for removing the warning? In
csharp we achieve very easily see the following code
To remove the warning
class Home
{
public void Fan()
{
Console.WriteLine("Home--->Fan");
}
}
class Hotel:Home
{
new public void Fan()
{
Console.WriteLine("Hotel--->Fan");
}
}
class Building
{
static void Main(string[] args)
{
Home objhome = new Home();
Hotel objhotel = new Hotel();
objhome.Fan();
objhotel.Fan();
}
}
Now you have to see the situation like this also just go through the program for a minute
See in this case:
class Home
{
public void Fan()
{
Console.WriteLine("Home--->Fan");
}
}
class Hotel:Home
{
new public void Fan()
{
Console.WriteLine("Hotel--->Fan");
}
}
class Building
{
static void Main(string[] args)
{
Home objhome = new Home();
Hotel objhotel = new Hotel();
objhome = objhotel;
objhome.Fan();
Console.Read();
}
}
Output:
Home--->Fan
Finally the better solution is:
class Home
{
public virtual void Fan()
{
Console.WriteLine("Home--->Fan");
}
}
class Hotel:Home
{
public override void Fan()
{
Console.WriteLine("Hotel--->Fan");
}
}
class Building
{
static void Main(string[] args)
{
Home objhome = new Home();
Hotel objhotel = new Hotel();
objhome = objhotel;
objhome.Fan();
Console.Read();
}
}
Hotel--->Fan