Shadowing is used to provide a new implementation for the base class method and helps protect against subsequent base class modification. Overriding allows you to rewrite a base class function with a different definition and achieve polymorphism.
In the context of .NET programming, particularly in languages like C#, shadowing and overriding are both mechanisms to change the behavior of methods or properties inherited from a base class. However, they achieve this in different ways:
- Shadowing (also known as Method Hiding):
- Shadowing allows a derived class to provide a new implementation for a member (method or property) that is already defined in the base class.
- In shadowing, the derived class redefines a member with the same signature as a member in the base class, effectively hiding the base class member within the derived class.
- When an instance of the derived class is used, calling the member will execute the implementation defined in the derived class, not the one defined in the base class.
- Shadowing is accomplished using the
new
keyword in C#.
Example of shadowing in C#:
class BaseClass
{
public void Print()
{
Console.WriteLine("BaseClass");
}
}
class DerivedClass : BaseClass
{
public new void Print()
{
Console.WriteLine("DerivedClass");
}
}
- Overriding:
- Overriding, on the other hand, allows a derived class to provide a specialized implementation for a method or property that is defined in the base class.
- With overriding, the base class method or property is replaced with a new implementation in the derived class.
- When an instance of the derived class is used, calling the member will execute the implementation defined in the derived class, even if it is invoked through a reference to the base class.
- Overriding is achieved using the
override
keyword in C#.
Example of overriding in C#:
class BaseClass
{
public virtual void Print()
{
Console.WriteLine("BaseClass");
}
}
class DerivedClass : BaseClass
{
public override void Print()
{
Console.WriteLine("DerivedClass");
}
}
In summary, the key difference lies in how they handle method resolution: shadowing hides the base class member in the derived class, while overriding replaces the base class member with a new implementation in the derived class.