SEMrush

Method Overriding in java

Method overriding : Overriding a method is a concept that allows us to declare a method in subclass even though the method is already present in parent class .
A method is said to be Overridden when it is implemented again in a different way in a child class which extends the parent class. 
Example :
This can be seen in the following example .
Audi class here extends Car class.
Note here that both the classes Audi and Car, have a common method void speed(). Audi class gives here its own implementation to the speed()method .
That means Audi class is overriding the method speed().
class Car{
   public void speed()
   {
      System.out.println("Car runs at a high speed");
   }
}
class Audi extends Car{
   public void speed (){
      System.out.println("Audi is the fastest");
   }
   public static void main( String args[]) {
      Audi obj = new Audi ();
      obj. speed ();
   }
}

Output:
Audi is the fastest  

What are the Advantages of method overriding ?
Child class can have its own implementation for an inherited method without modifying the method in the parent class/base class .

Method Overriding in dynamic method dispatchWe can assign the base class reference to a child class object .This technique is called Dynamic method technique .
In the example below that the base class reference is assigned to child class object.
Class MyParentCar{  
   public void displayColor()
   {
      System.out.println("displayColor() method of parent class");
   }
   public void sound()
   {
      System.out.println("sound() method of parent MyParentCar  class");
   }          
}

class ChildAudi extends MyParentCar {
   public void displayColor (){
      System.out.println("displayColor() method of Child Audi class");
   }
   public void speed(){

      System.out.println("speed () method of Child class");
   }

   public static void main( String args[]) {
      //Parent class reference to child class object
      MyParentCar obj = new ChildAudi ();
      obj.displayColor();
      obj.sound ();
   }
}

Output:
displayColor() method of ChildAudi class
sound() method of parent MyParentCar  class  

Note: We can only call methods which are already present in the Base Class also.
We will not be able to call speed() because it is not present in the base class.
if we try to call the speed () method with obj. speed() ,  we would get compilation error as follows:
Exception in thread "main" java.lang.Error: Unresolved compilation