Introduction
C# is the modern Object-Oriented Programming Language. It is very similar to the java programming language. It is developed by Microsoft and the first version was released in 2002. The latest version of C# is 8.0. In this blog, we will be discussing Method Overriding and Method Hiding and the difference between them.
Method Overriding
It is one of the most powerful techniques in C#. Method overriding is the technique using which one can implement the functions of the base class in the derived class. One can update the implementation, usage, and behaviors of the functions of the parent class in the derived class. Using this technique, Runtime Polymorphism is implemented in C#.
In the above picture, we can see that the BMW class is the derived class and the Vehicle class is the parent class. We are overriding the numberOfTyres() and honk() function in the BMW class.
using System;
// Base class
class Vehicle {
// virtual method
public virtual void numberOfTyres()
{
Console.WriteLine("A vehicle can have 2, 3, 4, 6, 8 tyres");
}
public virtual void honk()
{
Console.WriteLine("A vehicle is honking");
}
public void accelerate()
{
Console.WriteLine("Vehicle is accelerating");
}
}
// Derived class
class BMW : Vehicle {
// Here numberOfTyres method is overridden
public override void numberOfTyres()
{
Console.WriteLine("BMW has 4 tyres");
}
public override void honk()
{
Console.WriteLine("BMW is honking");
}
}
class GFG {
// Main Method
public static void Main()
{
Vehicle obj;
// Creating object of the base class
obj = new Vehicle();
// Invoking method of the base class
obj.numberOfTyres();
// Creating object of the derived class
obj = new BMW();
// Invoking method of derived class
obj.numberOfTyres();
}
}
Output
A vehicle can have 2, 3, 4, 6, 8 tyres
BMW has 4 tyres