Method Overriding in C#: Implementing Runtime Polymorphism
Understand method overriding in C#, a key object-oriented programming concept. This guide explains how to override methods in derived classes, the use of the `virtual` and `override` keywords, and how method overriding enables runtime polymorphism.
Method Overriding in C#
Introduction
Method overriding in C# allows a derived class (subclass) to provide a specific implementation for a method that's already defined in its base class (superclass). This is a key concept in object-oriented programming, enabling runtime polymorphism—the ability to determine which method to execute based on the object's type at runtime.
Implementing Method Overriding
To override a method, you need to use the `virtual` keyword in the base class method declaration and the `override` keyword in the derived class method declaration.
Keywords: `virtual` and `override`
virtual
: In the base class, thevirtual
keyword indicates that the method can be overridden in derived classes.override
: In the derived class, theoverride
keyword explicitly indicates that the method is overriding a method from the base class.
Example: Overriding the `eat()` Method
This example shows a base class `Animal` with a virtual `eat()` method and a derived class `Dog` that overrides it.
Method Overriding Example
using System;
public class Animal {
public virtual void eat() {
Console.WriteLine("Eating...");
}
}
public class Dog : Animal {
public override void eat() {
Console.WriteLine("Eating bread...");
}
}
public class TestOverriding {
public static void Main() {
Dog d = new Dog();
d.eat(); // Calls the Dog's eat() method
}
}
Example Output
Eating bread...
Explanation
When `d.eat()` is called, the runtime determines that `d` is a `Dog` object, and therefore, the `Dog` class's `eat()` method (the overridden version) is executed. This is runtime polymorphism in action.
Important Considerations
- Signature Matching: The overridden method in the derived class must have the *exact same signature* (name, return type, and parameters) as the base class method.
- Access Modifiers: The access modifier (e.g., `public`, `protected`, `private`) of the overridden method can be the same or more accessible than the base class method (e.g., you can't override a `public` method with a `private` one).
- Virtual Methods Only: Only virtual methods can be overridden.
Conclusion
Method overriding is a powerful tool for extending and specializing the behavior of base classes in an object-oriented manner. It's fundamental to achieving runtime polymorphism and creating flexible, maintainable code.