Method overriding is an example of runtime polymorphism. In method overriding, a subclass overrides a method with the same signature as that of in its superclass. During compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object.
We can override a method at any level of multilevel inheritance. See the example below to understand the concept −
Example
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"); } } class Puppy extends Dog { public void move() { System.out.println("Puppy can move."); } } public class Tester { public static void main(String args[]) { Animal a = new Animal(); // Animal reference and object Animal b = new Puppy(); // Animal reference but Puppy object a.move(); // runs the method in Animal class b.move(); // runs the method in Puppy class } }
Output
Animals can move Puppy can move.