Function Overriding Example
In this example, the Start method is overridden in the derived class SportsCar using the override keyword. This demonstrates runtime polymorphism.
C# Example:
using System;
class Car
{
public virtual void Start()
{
Console.WriteLine("Car is starting.");
}
}
class SportsCar : Car
{
public override void Start()
{
Console.WriteLine("SportsCar is starting with turbo!");
}
}
class Program
{
static void Main()
{
Car myCar = new Car();
myCar.Start();
SportsCar mySportsCar = new SportsCar();
mySportsCar.Start();
Car carRef = new SportsCar();
carRef.Start();
}
}
Output:
Car is starting.
SportsCar is starting with turbo!
SportsCar is starting with turbo!
No comments:
Post a Comment