C# Method Overriding
Method overriding in C# is a fundamental concept in object-oriented programming (OOP) that allows a derived class (subclass) to provide a specific implementation of a method that is already defined in its base class (superclass). This capability enables polymorphism, where a method can behave differently based on the object that invokes it.
Key Concepts of Method Overriding
Inheritance: Method overriding is only possible in the context of inheritance. A derived class inherits members (including methods) from its base class.
Virtual Methods: To allow a method in the base class to be overridden, it must be declared with the
virtual
keyword. This indicates that the method can be redefined in any derived class.Override Keyword: In the derived class, the method that overrides the base class method must be marked with the
override
keyword. This indicates that you are providing a new implementation of an inherited method.Base Keyword: Within the overriding method, you can call the base class implementation using the
base
keyword if needed.
Syntax for Method Overriding
Here's the basic syntax for method overriding:
Example of Method Overriding
Here’s a practical example to illustrate method overriding in C#:
Explanation of the Example
Base Class (
Animal
): TheAnimal
class has a virtual methodSpeak()
that outputs a generic message indicating the animal speaks.Derived Classes (
Dog
andCat
): TheDog
andCat
classes inherit fromAnimal
and override theSpeak()
method to provide specific implementations for dogs and cats, respectively.Polymorphism: In the
Main
method,myDog
andmyCat
are declared as typeAnimal
, but they are instantiated asDog
andCat
objects. WhenSpeak()
is called on these objects, the overridden methods inDog
andCat
are executed, demonstrating polymorphic behavior.
Key Points to Remember
Accessibility: The overriding method must have the same accessibility level as the method it overrides (e.g., both must be
public
,protected
, etc.).Return Type: The return type of the overriding method must match the return type of the base method or be a derived type (covariant return type).
Non-Virtual Methods: Methods that are not declared as
virtual
in the base class cannot be overridden. They can be hidden using thenew
keyword, but this does not provide polymorphic behavior.
Conclusion
Method overriding is a powerful feature in C# that allows for dynamic method dispatch and enables polymorphism, allowing objects of derived classes to be treated as objects of the base class. By utilizing method overriding, developers can create more flexible and maintainable code, making it easier to extend functionality without modifying existing code. This principle is central to achieving abstraction and encapsulation in object-oriented programming.