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
Listinstead ofArrayList). - Avoid Downcasting: Try to avoid manually forcing a parent back into a child type (
(Pig) myAnimal) unless absolutely necessary. Useinstanceofto check first.
Practice Exercises
- The Payment System: Create a parent
Paymentclass and childrenCreditCardandPayPal. Write a method that processes a payment without knowing which type it is. - Instance Check: Use the
instanceofoperator to check if anAnimalvariable is actually holding aDog. - The Dynamic Array: Create an array of type
Animal[]and fill it with different animal objects. Loop through and call a shared method.