Polymorphism: Many Forms

Polymorphism: Many Forms in Java: Polymorphism (Greek for "Many Forms") is the ability of an object to take on many forms.

Concept Explanation

Polymorphism (Greek for "Many Forms") is the ability of an object to take on many forms. Specifically, it allows a parent-type variable to hold a child-type object and still behave correctly.

Imagine a Universal Remote. You press the "Play" button.

  • If it's pointing at a DVD Player, it plays a disc.
  • If it's pointing at YouTube, it plays a stream.

The action is the same, but the result depends on what object is being used.


Syntax or Core Structure

Animal myAnimal = new Pig(); // Parent type, Child object
myAnimal.animalSound();      // Prints "Oink" because the OBJECT is a pig

Why use this?

It allows you to write code that works with any type of animal without needing to know exactly which one it is. You can have a list of 100 different animals and just call .makeSound() on all of them in a loop.


Best Practices

  • Upcasting: Always use the most general type possible for your variables (e.g., use List instead of ArrayList).
  • Avoid Downcasting: Try to avoid manually forcing a parent back into a child type ((Pig) myAnimal) unless absolutely necessary. Use instanceof to check first.

Practice Exercises

  1. The Payment System: Create a parent Payment class and children CreditCard and PayPal. Write a method that processes a payment without knowing which type it is.
  2. Instance Check: Use the instanceof operator to check if an Animal variable is actually holding a Dog.
  3. The Dynamic Array: Create an array of type Animal[] and fill it with different animal objects. Loop through and call a shared method.