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
- Parent reference can hold child objects
- Actual method called depends on object type
- This is runtime polymorphism
Related Inheritance exercises
- Practice Abstract Classes in Java
- Practice Implementing Interface in Java
- Practice Employee Hierarchy in Java
Practice all Inheritance exercises · Run this idea in the Java compiler