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




KOTLIN - 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 {

	fun breathe() {
		println("Breathes oxygen from Air")
	}
}



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


println("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 :



open class LivingBeing {

    open fun breathe() {
        println("Breathes oxygen from Air")
    }
}

class Fish: LivingBeing() {

    override fun breathe() {
        println("Breathes oxygen from Water")
    }
}

fun main() {
    var fish1 = Fish()
    fish1.breathe()
}


Output :



  Breathes oxygen from Water

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


open class LivingBeing {
	open fun breathe() {
		println("Breathes oxygen from Air")
	}
}

Just note that we have used the open keyword before the LivingBeing class definition,


open class LivingBeing

And also used the open keyword before the breathe() function,


open fun breathe()

That is because we will be inheriting from the LivingBeing class and would be overriding/redefining the breathe() method.


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.


override fun breathe() {
	println("Breathes oxygen from Water")
}

So, with fish object of Fish class,


var fish1 = 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.