Dynamic Binding
Dynamic binding, also known as late binding, means that the method to execute is determined at runtime based on the actual object being referred to. It is used in runtime polymorphism.
Key Points:
- Resolved at runtime.
- Occurs during method overriding.
- Requires
virtualandoverride. - Base class reference can call derived class methods.
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 fast!");
}
}
class Program
{
static void Main()
{
Car c = new SportsCar();
c.Drive();
}
}
Output:
SportsCar is driving fast!
No comments:
Post a Comment