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
raja
Published on 15-Feb-2019 11:51:39
Advertisements