🔴 Advanced · Lesson 24
Abstract Class vs Interface
Abstract Class vs Interface
Two Ways to Define a Contract
Both abstract classes and interfaces force child classes to implement certain methods, but they work differently.
Abstract Class
abstract class Shape {
abstract public function area(); // no body
public function describe() { // can have real methods
return "I am a shape";
}
}
class Circle extends Shape {
public function area() { return 3.14 * 5 * 5; }
}
Interface
interface Payable {
public function pay(); // only signatures
}
class Order implements Payable {
public function pay() { echo "Paid"; }
}
Difference
| Abstract Class | Interface |
|---|---|
| can have real methods + properties | only method signatures |
| extends (one only) | implements (many allowed) |
Summary
- Abstract class: mix of real and abstract methods; single inheritance.
- Interface: only signatures; a class can implement many.
Contract Define करने के दो तरीके
Abstract classes और interfaces दोनों child classes को कुछ methods implement करने पर मजबूर करते हैं, पर अलग तरह काम करते हैं।
Abstract Class
abstract class Shape {
abstract public function area(); // no body
public function describe() { // real method भी हो सकती है
return "I am a shape";
}
}
class Circle extends Shape {
public function area() { return 3.14 * 5 * 5; }
}
Interface
interface Payable {
public function pay(); // सिर्फ signatures
}
class Order implements Payable {
public function pay() { echo "Paid"; }
}
अंतर
| Abstract Class | Interface |
|---|---|
| real methods + properties हो सकती हैं | सिर्फ method signatures |
| extends (सिर्फ एक) | implements (कई) |
सारांश
- Abstract class: real और abstract methods का मिश्रण; single inheritance।
- Interface: सिर्फ signatures; class कई implement कर सकती है।