Polymorphism Demo in Java: Explanation & Practice

Demonstrate runtime polymorphism

Problem summary

Create Animal array with Dog and Cat objects, each with unique sound.

Starter code

// Animal with abstract sound()
// Dog: sound() prints "Woof"
// Cat: sound() prints "Meow"

public class Main {
    public static void main(String[] args) {
        // Create Animal array with Dog and Cat
        // Loop and call sound() on each
    }
}

Expected output and test cases

  • Polymorphic sounds
    Woof
    Meow

Hints

  1. Parent reference can hold child objects
  2. Actual method called depends on object type
  3. This is runtime polymorphism

Related Inheritance exercises

Practice all Inheritance exercises · Run this idea in the Java compiler