Function Overriding
Function overriding means defining the same method in a derived class that already exists in the base class, using the same name, parameters, and return type. It is used to change the inherited behavior.
Key Points
- Requires
virtualin the base class. - Requires
overridein the derived class. - Method name, parameters, and return type must match exactly.
- Used for runtime polymorphism.
C# Example:
class Car
{
public virtual void Drive()
{
Console.WriteLine("Car is driving.");
}
}
class SportsCar : Car
{
public override void Drive()
{
Console.WriteLine("SportsCar is driving very fast!");
}
}
class Program
{
static void Main()
{
Car c = new SportsCar();
c.Drive();
}
}
Output:
SportsCar is driving very fast!
No comments:
Post a Comment