What is it?
An abstract class is a partially-built class — it can have shared code AND require child classes to implement certain methods. An interface is a pure contract — it defines what methods must exist but provides zero code.
Why does it matter?
Choosing wrong creates fragile designs. Use the wrong one and you end up with duplicate code or impossible-to-reuse structures. This is one of the most commonly asked OOP interview questions at TCS, Infosys, and Google.
Learn abstract classes vs interfaces with real-world examples and guidelines.
Real-World Use Cases
- 🔷 Shape hierarchy - Shape abstract class holds color property and describe() method. Circle, Square, Triangle each implement the abstract area() method differently.
- 📤 Export contracts - Exportable interface ensures every report type has exportToCsv() and exportToJson(). The interface itself has no code.
- 🗄️ Database drivers - AbstractDatabase holds shared connection logic. MySQLDriver and PostgreSQLDriver each implement the abstract query() method.
- 🔔 Notification channels - Notifiable interface with send(). SMS, Email, Slack classes all implement it — completely unrelated classes, same contract.
Abstract Class — Partial Blueprint
Use when:
abstract class Animal {
public function eat() {
echo "Eating...";
}
abstract public function sound();
}
class Dog extends Animal {
public function sound() {
echo "Bark";
}
}
Interface — Pure Contract
Use when:
interface Payment {
public function pay($amount);
}
class PayPal implements Payment {
public function pay($amount) {
echo "Paid $amount via PayPal";
}
}
Decision Guide
| Requirement | Use |
|---|---|
| Share common code | Abstract Class |
| Define only rules/contract | Interface |
| Need properties | Abstract Class |
| Need method implementation | Abstract Class |
| Multiple inheritance-like behavior | Interface |
| Unrelated classes follow same contract | Interface |
Q: Can an abstract class implement an interface?
Yes. An abstract class can implement an interface without providing all methods — leaving them abstract for child classes. Useful for sharing common code among classes that satisfy the same contract.
Comments (0)
No comments yet. Be the first!
Leave a Comment