Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




RUBY - METHOD OVERRIDING


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.


Example :



class LivingBeing

	def breathe()
		puts "Breathes oxygen from Air"
	end
end		



So, the breathe() method has a print statement,


puts "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.


Example :



class LivingBeing

	def breathe()
		puts "Breathes oxygen from Air"
	end
end	

class Fish < LivingBeing

	def breathe()
		puts "Breathes oxygen from Water"
	end
end	
	
fish1 = Fish.new()
fish1.breathe()


Output :



  Breathes oxygen from Water

And all we have done is, created the LivingBeing being class with the breathe() method.


class LivingBeing:

	def breathe(self):
		puts "Breathes oxygen from Air")

Then we have created the Fish class, inheriting the LivingBeing class.


class Fish < LivingBeing

	def breathe()
		puts "Breathes oxygen from Water"
	end
end

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 = Fish.new()

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.