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




Java - Method Overriding

Method overriding is redefining the same method of the Parent Class in the Child class.

Let's understand this with an example.


Story :

Say, the Supreme God has created a 'LivingBeing' class. And made a rule that all living beings should breathe oxygen from air. And he defined this rule in a breathe() method.

class LivingBeing{

  void breathe(){
    System.out.println("Breathes oxygen from air.");
  }
}


Story :

Now, the Fish creator God was in problem as a Fish should breathe Oxygen from water and not from air.

To solve this problem Overriding came into picture. i.e. In the 'Fish' class, he can redefine the breathe() method/behavior again.

class Fish extends LivingBeing{

  public void breathe(){

    System.out.println("Breathes oxygen from water.");
  }
}


In the above code, the 'Human' class extends the 'LivingBeing' class.


class Fish extends LivingBeing

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.

Now, let us write the main class which create objects :


class ApplicationTest{
  public static void main(String[] arg){

    Fish fish = new Fish();
    fish.breathe();// Calls the breathe() of Fish
  }
}

Output :


   Breathes oxygen from air

In the above scenario with 'fish' object of 'Fish' class, we are able to call the breathe() method defined in the 'Fish' class itself. And ignored the breathe() method defined in the parent class 'LivingBeing'.


fish.breathe();