Runtime Polymorphism in Java


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.

Example

See the example below to understand the concept −

 Live Demo

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
   }
}

Output

This will produce the following result −

Animals can move
Dogs can walk and run

Updated on: 17-Jun-2020

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements