Using run-time polymorphism in Java


A single action can be performed in multiple ways using the concept of polymorphism. Run-time polymorphism can be performed by method overriding. The overridden method in this is resolved at compile time.

A program that demonstrates run-time polymorphism in Java is given as follows:

Example

 Live Demo

class Animal {
   void sound() {
      System.out.println("Animal makes sound");
   }
}
class Cat extends Animal {
   void sound() {
      System.out.println("Cat Meows");
   }
}
class Dog extends Animal {
   void sound() {
      System.out.println("Dog Barks");
   }
}
class Cow extends Animal {
   void sound() {
      System.out.println("Cow Moos");
   }
}
public class Demo {
   public static void main(String[] args) {
      Animal a;
      a = new Cat();
      a.sound();
      a = new Dog();
      a.sound();
      a = new Cow();
      a.sound();
   }
}

Output

Cat Meows
Dog Barks
Cow Moos

Rishi Raj
Rishi Raj

I am a coder

Updated on: 30-Jul-2019

272 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements