- Get link
- X
- Other Apps
Inheritance & Polymorphism
Side‑by‑side Java snippet · similarity & difference
🧬 Inheritance
extends
// Parent class class BankAccount { protected double balance; public void deposit(double amt) { balance += amt; System.out.println("Deposited: " + amt); } } // Child class inherits structure + behavior class SavingsAccount extends BankAccount { private double interestRate; public void addInterest() { balance += balance * interestRate; } } // Usage – reuse via inheritance SavingsAccount sa = new SavingsAccount(); sa.deposit(500); // inherited method sa.addInterest(); // own method
🎭 Polymorphism
@Override
// Parent class defines common interface class BankAccount { protected double balance; public void deposit(double amt) { balance += amt; System.out.println("Deposited: " + amt); } // overridden by subclasses public void accountType() { System.out.println("Generic account"); } } class SavingsAccount extends BankAccount { @Override public void accountType() { System.out.println("Savings account"); } } // Same call → different behavior BankAccount acc = new SavingsAccount(); acc.accountType(); // "Savings account"
✅ Similarities
- Both use the
extendskeyword to build a parent–child relationship. - Both rely on the same parent class (
BankAccount) as a shared blueprint. - Child class (
SavingsAccount) automatically inherits fields likebalanceand methods likedeposit(). - Both enable code reuse — common logic lives only in the superclass.
- Both are core pillars of OOP and appear together in real class diagrams.
⚠️ Differences
- Purpose: Inheritance = reuse structure; Polymorphism = vary behavior.
- Mechanism: Inheritance uses
extends; polymorphism uses@Override(method overriding). - Behavior: Inherited method
deposit()runs identically in child; overriddenaccountType()runs differently. - Reference type: Polymorphism allows
BankAccount acc = new SavingsAccount()— inheritance alone does not. - Diagram symbol: Inheritance = hollow triangle
▷; Polymorphism = often shown via override notes or dynamic dispatch.
🔑 Key insight: The two snippets share the same parent class and inheritance structure —
but the right side adds overriding, turning a static “is‑a” relationship into a dynamic,
interchangeable behavior. Inheritance gives you the blueprint; polymorphism lets you swap the behavior
behind a common interface.
Comments