Method overriding is done through inheritance, it allows us to define a method at a derived class with the same name present in a base class with the same signature and same return type then the method in a base class is said to be overridden.
In method overriding, the base class method uses virtual keyword while the derived class method uses override keyword.
Method overriding is one of the ways through which C# achieves Run Time Polymorphism (Dynamic Polymorphism). The decision made to call the required function is done at the run time. Hence, it is a Runtime polymorphism.
Example: C# program for method overriding.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | using System; namespace Program { public class Animal { public virtual void sleep() { Console.WriteLine("Animals Sleeps"); } } public class Dog: Animal //inheriting Animal class { public override void sleep() { Console.WriteLine("Dog Sleeps"); } } public class OverrideMain { public static void Main() { Animal obj = new Dog(); obj.sleep(); obj = new Animal(); obj.sleep(); } } } |
Output:
Dog Sleeps
Animals Sleeps