|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
IntroductionMethod hiding in C# is similar to the function overriding feature in C++. Functions of the base class are available to the derived class. If the derived class is not happy, one of the functions available to it from the base class can define its own version of the same function with the same function signature, just differing in implementation. This new definition hides the base class definition. Take the following program for example. P1.csclass BC
{
public void Display()
{
System.Console.WriteLine("BC::Display");
}
}
class DC : BC
{
}
class Demo
{
public static void Main()
{
DC obj = new DC();
obj.Display();
}
}
OutputBC::Display
The above program compiles and runs successfully to give the desired output. The above program consists of a base class For some unknown reason the derived class was not happy with the implementation of the P2.csclass BC
{
public void Display()
{
System.Console.WriteLine("BC::Display");
}
}
class DC : BC
{
public void Display()
{
System.Console.WriteLine("DC::Display");
}
}
class Demo
{
public static void Main()
{
DC obj = new DC();
obj.Display();
}
}
OutputDC::Display
On compilation the above program threw a warning which said P2.cs(11,15): warning CS0108: 'DC.Display()' hides inherited member
'BC.Display()'. Use the new keyword if hiding was intended. P2.cs(3,15):
(Location of symbol related to previous warning)
The compiler warns us about The above program compiles to produce an executable. We run the executable to get the desired output as shown above. The P3.csclass BC
{
public void Display()
{
System.Console.WriteLine("BC::Display");
}
}
class DC : BC
{
new public void Display()
{
System.Console.WriteLine("DC::Display");
}
}
class Demo
{
public static void Main()
{
DC obj = new DC();
obj.Display();
}
}
OutputDC::Display
The addition of the modifier new to the function P4.csclass BC
{
public void Display()
{
System.Console.WriteLine("BC::Display");
}
}
class DC : BC
{
new public void Display()
{
System.Console.WriteLine("DC::Display");
}
}
class TC : DC
{
}
class Demo
{
public static void Main()
{
TC obj = new TC();
obj.Display();
}
}
OutputDC::Display
The above program compiles and runs successfully to give the desired output. Class P5.csclass BC
{
public void Display()
{
System.Console.WriteLine("BC::Display");
}
}
class DC : BC
{
new public void Display()
{
System.Console.WriteLine("DC::Display");
}
}
class TC : DC
{
new public void Display()
{
System.Console.WriteLine("TC::Display");
}
}
class Demo
{
public static void Main()
{
TC obj = new TC();
obj.Display();
}
}
OutputTC::Display
The above program comples and runs successfully to give the desired output.
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||