![]() |
VOOZH | about |
Method overriding in C# allows a derived class to provide a new implementation of a method that is already defined in its base class. It is a key feature of runtime polymorphism.
Example: Program to demonstrate Method Overriding in detail.
Dog is running. Animal is eating. Dog is barking.
In C#, three keywords are used for Method Overriding which are listed below:
This keyword is used in the base class to define a method that can be overridden in a derived class.
Example 1: Method overriding using virtual keyword.
Dog is running.
Explanation: The Move() method in the Animal class is marked as virtual, which allows it to be overridden in the Dog class using the override keyword.
Example 2: Method overriding using virtual and override modifiers.
Base class Derived class
Explanation:
This keyword is used in the derived class to provide a specific implementation of a method defined in the base class.
Example: Method overriding using override keyword.
Dog is running.
Explanation: The Move() method in the Dog class uses the override keyword to change the behavior of the Move() method defined in the Animal class.
This method is used to access members(methods, properties or constructors) of the base class from within a derived class.
Use of Base Keyword:
Example 1: Method overriding using Base keyword.
Animal is moving. Dog is running.
Example 2: How the base Keyword specifies the calling of base-class constructor from the derived class, when derived class instances are created.
Output:
Example 3: How base keyword specifies the base-class constructor called from derived class and calling a method using the base keyword from the derived class.
Output: