Method overriding is redefining the same method of the Parent Class in the Child class.
Let us understand with the below example.
So, we have the LivingBeing class that has a breathe() method.
class LivingBeing
{
public void breathe()
{
System.Console.WriteLine("Breathes oxygen from Air");
}
}
So, the breathe() method has a print statement,
System.Console.WriteLine("Breathes oxygen from Air");That says, all Living Beings should Breathe oxygen from Air.
Now, let us create a Fish class and since Fish is also a LivingBeing. It should inherit the LivingBeing class.
But the only issue is, the breathe() method won't be valid for Fish. As a Fish breathe oxygen from water.
And this is where Method Overriding comes into picture.
Let us understand with the below example.
class LivingBeing
{
public void breathe()
{
System.Console.WriteLine("Breathes oxygen from Air");
}
}
class Fish : LivingBeing
{
public void breathe()
{
System.Console.WriteLine("Breathes oxygen from Water");
}
}
class CreateLivingBeing
{
public static void Main(string[] args)
{
Fish fish = new Fish();
fish.breathe();
}
}
And all we have done is, created the LivingBeing being class with the breathe() method.
class LivingBeing
{
public void breathe()
{
System.Console.WriteLine("Breathes oxygen from Air");
}
}Then we have created the Fish class, inheriting the LivingBeing class.
class Fish: LivingBeing() {
override fun breathe() {
println("Breathes oxygen from Water")
}
}So, by Inheritance, the Fish class should get the breathe() method/behaviour of the LivingBeing class.
And since we don't want the breathe() method/behaviour of the LivingBeing class. We have redefined or overridden the breathe() method in our Fish class using the override keyword.
public void breathe()
{
System.Console.WriteLine("Breathes oxygen from Water");
}So, with fish object of Fish class,
Fish fish = new Fish();
Now if you see the output.
Breathes oxygen from Water
We are able to call the breathe() method defined in the Fish class itself.
fish1.breathe();
And ignored the breathe() method defined in the parent class LivingBeing.