Inheritance & Polymorphism
Reusing code across classes, and letting the same action behave differently.
Inheritance
Inheritance lets a class (child) reuse properties and methods of another class (parent), avoiding duplicate code and modeling 'is-a' relationships â e.g. a Dog 'is an' Animal.
Polymorphism
Polymorphism means 'many forms' â the same method name behaves differently depending on the object calling it. This is achieved via method overriding (runtime) or method overloading (compile-time).
Example
An Animal class might have a generic sound() method. A Dog class overrides it to bark(), and a Cat class overrides it to meow() â calling sound() on each gives a different result, even though the method name is the same.
đ Real-World Use
Payment systems use polymorphism: a single `processPayment()` call works whether the actual object is a CreditCard, UPI, or Wallet class â each implements the method differently, but the calling code stays the same.
đĄ Pro Tip
In interviews, be ready to explain the difference between overloading (same method name, different parameters, decided at compile time) and overriding (child class redefines parent's method, decided at runtime) â this is one of the most repeated OOPs questions.
đ§Ē Quick Self-Test
Check what you just learned â no pressure, just practice.
1. Inheritance is best described as modeling what relationship?
2. What is polymorphism?