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 { breathe() { document.write("Breathes oxygen from Air") } }
So, the breathe() method has a document.write statement,
document.write("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.
<html> <body> <script> class LivingBeing { breathe() { document.write("Breathes oxygen from Air") } } class Fish extends LivingBeing { breathe() { document.write("Breathes oxygen from Water") } } fish1 = new Fish() fish1.breathe() </script> </body> </html>
And all we have done is, created the LivingBeing being class with the breathe() method.
class LivingBeing { breathe() { document.write("Breathes oxygen from Air") } }
Then we have created the Fish class, inheriting the LivingBeing class.
class Fish extends LivingBeing { breathe() { document.write("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.
So, with fish object of Fish class,
fish1 = 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.