"Karmanyevadhikaraste ma phaleshu kadachana, Ma karma phala hetur bhurmatey sangostva akarmani."

Overriding

Same method name in parent class and child class..
  • The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass.
    • The access level cannot be more restrictive than the overridden method's access level. For example: if the superclass method is declared public then the overridding method in the sub class cannot be either private or protected.
      • A method declared final cannot be overridden.
      • A method declared static cannot be overridden but can be re-declared.
  • A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.
  • A subclass in a different package can only override the non-final methods declared public or protected.
  • An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. 



Benifit:
 ability to define a behavior that's specific to the subclass type which means a subclass can implement a parent class method based on its requirement.

class Animal{

   public void move(){
      System.out.println("Animals can move");
   }
}

class Dog extends Animal{

   public void move(){
      System.out.println("Dogs can walk and run");
   }
}

public class TestDog{

   public static void main(String args[]){
      Animal a = new Animal(); // Animal reference and object
      Animal b = new Dog(); // Animal reference but Dog object

      a.move();// runs the method in Animal class

      b.move();//Runs the method in Dog class
   }
}
This would produce the following result:
Animals can move
Dogs can walk and run

Using the super keyword:

When invoking a superclass version of an overridden method the super keyword is used.
class Animal{

   public void move(){
      System.out.println("Animals can move");
   }
}

class Dog extends Animal{

   public void move(){
      super.move(); // invokes the super class method
      System.out.println("Dogs can walk and run");
   }
}

public class TestDog{

   public static void main(String args[]){

      Animal b = new Dog(); // Animal reference but Dog object
      b.move(); //Runs the method in Dog class

   }
}
This would produce the following result:
Animals can move
Dogs can walk and run