Junior — Middle
Is it possible to change the functionality of a method by overriding it in a subclass?
sobes.tech AI
Answer from AI
Yes, in C# it is possible to change the functionality of a method by overriding it in a derived class. For this, the base method must be declared with the virtual keyword, and in the derived class, it can be overridden using the override keyword.
Example:
class BaseClass
{
public virtual void ShowMessage()
{
Console.WriteLine("Message from the base class");
}
}
class DerivedClass : BaseClass
{
public override void ShowMessage()
{
Console.WriteLine("Overridden message from the derived class");
}
}
Calling the ShowMessage method on an object of DerivedClass will execute the overridden version of the method.