How to Implement Polymorphism in Java


In this example we will show you how to implement polymorphism in Java.

Source Code

package com.beginner.examples;

class Animal {
  public void yell() {
    System.out.println("yell...");
  }
}

// implement java polymorphism
class Cat extends Animal {
  public void yell() {
    System.out.println("meow...");
  }
}

// implement java polymorphism
class Dog extends Animal {
  public void yell() {
    System.out.println("woof...");
  }
}

public class Polymorphism {
  public static void main(String[] args) {
    Animal a = new Animal();
    Animal c = new Cat();
    Animal d = new Dog();

    a.yell();
    c.yell();
    d.yell();
  }
}

Output:

yell...
meow...
woof...
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments