Advanced Topic 43 of 54 Programming Fundamentals
Polymorphism
Treating different types uniformly through a shared interface.
How it works
Polymorphism lets code call the same method on objects of different types and get type-specific behavior. Subtype polymorphism uses dynamic dispatch through a virtual method table, parametric polymorphism uses generics, and ad hoc polymorphism uses overloading. The caller depends on an abstraction, not on concrete classes.
Step-by-step walkthrough
- Code calls area() on a shape reference.
- If the object is a Circle, Circle's version runs.
- If it is a Square, Square's version runs.
- If it is a Triangle, Triangle's version runs.
- The caller never checks the type, new shapes simply plug in.
Where it is used
A draw() call working on every Shape without knowing the subtype, a payment processor that accepts any PaymentMethod and a logging interface with several backends are examples. It removes long type-checking switch statements.
Common pitfall
Subclasses that violate the base-class contract break callers, which is the Liskov substitution principle. Overloading can cause ambiguity and surprising method selection. Excessive type checks with instanceof suggest polymorphism is being bypassed. Design interfaces around behavior and test every implementation against the same contract.
Where it fits in the course
Polymorphism is topic 43 of 54 in Programming Fundamentals, rated Advanced. It follows Inheritance. The next topic is Abstraction.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Programming Fundamentals quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Programming Fundamentals quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Polymorphism?
Where do people use Polymorphism?
What is the most common mistake with Polymorphism?
What should I learn before this topic?
How can I practice it?
Is Polymorphism hard to learn?
How long does it take to learn Polymorphism?
Which topics are related to Polymorphism?
What should I study after Polymorphism?
Related topics
- Inheritance (Programming Fundamentals)
- Abstraction (Programming Fundamentals)
- Encapsulation (Programming Fundamentals)
- Interfaces and Abstract Classes (Programming Fundamentals)