OVERRIDING METHOD

 
In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass.The benefit of overriding is: ability to define a behavior that's specific to the sub class type. Which means a subclass can implement a parent class method based on its requirement.
In object oriented terms, overriding means to override the functionality of any existing method.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
   }
}

O/P

java overriding