- Get link
- X
- Other Apps
Here is the Blogger-ready HTML using a with 2 columns to present the side‑by‑side code comparison, similarities, and differences.
```html
| 🧬 Inheritance extends | 🎭 Polymorphism @Override |
|---|---|
// Parent class class BankAccount { protected double balance; public void deposit(double amt) { balance += amt; System.out.println("Deposited: " + amt); } } // Child 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 sa.addInterest(); // own |
// Parent defines common interface class BankAccount { protected double balance; public void deposit(double amt) { balance += amt; System.out.println("Deposited: " + amt); } // overridden by subclass 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
|
|
⚠️ Differences
|
|
🔑 Key insight: Both 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 the blueprint; polymorphism lets you swap the behavior
behind a common interface.
Comments