C# Method Overriding

Method overriding is the mechanism where derived class defines the same method as parent class with more functionality in the chilled class. It provides runtime polymorphism in C#. It provides specific implementation to the method which is already defined in the base class. To perform method overriding, we need to use virtual keyword for base class method and override keyword for chilled class method. Let's see a simple example of method overriding

using System;
public class Animal 
{
            public void eat()
            {
                        Console.WriteLine("eating ....");
            }
}
public class Dog:Animal
{
            public void eat()
            {
                        Console.WriteLine("eating bread....");
            }
}
public class OverridingExample
{
            public static void Main (string[] args)
            {
                        Dog d=new Dog();
                        d.eat();
            }
}
Output
eating bread....
C# Method Overriding Example: with Multilevel inheritance: Let's see a simple example of method overriding with multilevel inheritance.
using System;
public class Bank
{
            public int getROI()
            {
                        return 4;
            }
}
public class RBI:Bank
{
            public int getROI()
            {
                        return 5;
            }
}
public class SBI:RBI
{
            public int getROI()
            {
                        return 6;
            }
}
public class OverridingExample
{
            public static void Main (string[] args)
            {
                        SBI s=new SBI();
                        Console.WriteLine(s.getROI());
            }
}                                                           
Output
6



ADVERTISEMENT
ADVERTISEMENT