All Courses
Runtime Polymorphism in Java

Runtime polymorphism in Java

April 30th, 2019 Java

Runtime Polymorphism in Java

When a  child  class extends a parent class then all of its variable and methods is accessible in the child class. But when the child class overrides one of the method of the parent class , then during the run time the method of the child class is called rather than the parent class, this is decided in the run time and not in the compile time, so this is referred as Dynamic method dispatch.

Example

class Animal{   public void run()
{  System.out.println("Animals can run");
}} class Deer extends Animal {
public void run() {
System.out.println("Deer can run faster than other animals"); }}
public class TestDeer
{    public static void main(String args[])
{       Animal a = new Animal();
// Animal reference and object      Animal b = new Deer();
// Animal reference but Deer object       a.run();
// runs the method in Animal class      b.run();
// runs the method in Deer class   }}
This will produce the following result

Output

Animals can run

Deer can run faster than other animals

Social Share:

0 responses on "Runtime polymorphism in Java"

Leave a Message

Your email address will not be published. Required fields are marked *