- Get link
- X
- Other Apps
Inheritance vs Polymorphism
Class Diagram Concept
| Aspect | ๐งฌ Inheritance | ๐ญ Polymorphism |
|---|---|---|
| ๐งฌ Inheritance |
is‑a hierarchy
code reuse
Definition & Purpose: A child class acquires attributes and methods from a parent class. Establishes an “is‑a” relationship (e.g., Car → Vehicle). Class diagram: solid line + hollow triangle ▷ pointing to the superclass. Example: SavingsAccount & CurrentAccount inherit from BankAccount. |
same call · different response
flexible design
Definition & Purpose: Different classes respond to the same method call in different ways. Allows objects of different subclasses to be treated as a common supertype. Class diagram: achieved via method overriding (same name, different implementation) or interfaces. Example: Shape has draw(); subclasses Circle, Square override it. |
| ๐ญ Polymorphism |
generalization arrow
parent‑child
Representation & Example: Solid line with hollow triangle ▷ (e.g., from SavingsAccount to BankAccount). Shared attributes: accountNumber, balance. Shared methods: deposit(), withdraw(). ⚡ Reuses structure & behavior |
method overriding
interfaces / abstract
Representation & Example: Same method signature, different implementations in subclasses. Shape.draw() is overridden by Circle.draw(), Square.draw(), Triangle.draw(). ๐ฏ Varies behavior through common interface |
๐ Key takeaway: Inheritance is about reusing structure through a parent‑child hierarchy;
polymorphism is about varying behavior through a common interface.
They often work together — polymorphism frequently relies on inheritance or interfaces.
Comments