Mada za sehemu hiiImplementing polymorphism with interfaces and abstract classesMada 3
- Designing abstract classes for common behaviour
- Implementing polymorphism with abstract classes or interfaces
- Performing overriding methods to implement polymorphic behaviour
Polymorphism means "many forms." In programming, it allows different classes to be treated as objects of the same type while behaving differently. Imagine a school payment system that handles tuition fees, library fines, and sports contributions. Each fee type calculates the total amount differently, but they all follow one common rule: every fee type must have a calculateAmount() method. This allows the programmer to write code that calls calculateAmount() without worrying about which specific fee type is being processed—the correct calculation runs automatically.
An abstract class is a special type of class that provides a general template or blueprint for other classes. It cannot be used to create objects directly. Instead, it defines common features that its child classes will share. Some of its methods are abstract methods, meaning they are declared without any implementation. These methods must be completed by the child classes that inherit from the abstract class.
An abstract method is a method declared in an abstract class that does not contain any code. It acts as a rule: Any class that inherits from this abstract class must provide its own version of this method.
Key Rules
- An abstract class cannot be instantiated directly (you cannot use
new Shape()). - Any class that extends an abstract class must implement all its abstract methods.
- A class can extend only one abstract class.
- Abstract classes can have both abstract methods (without body) and regular methods (with body).
When multiple classes share similar behaviour, an abstract class can serve as a parent to define the common structure, while letting child classes fill in the specific details. Each child class follows the same rule but uses the method in its own way.
Worked Example: Animal Sounds
<?php
// Abstract class Animal
abstract class Animal {
public $name;
public function __construct($name) {
$this->name = $name;
}
// Abstract method: must be implemented by child classes
abstract public function makeSound();
// Regular method: shared by all animals
public function describe() {
echo "$this->name is an animal.<br />";
}
}
// Dog class inherits from Animal
class Dog extends Animal {
public function makeSound() {
echo "$this->name says Woof!<br />";
}
}
// Cat class inherits from Animal
class Cat extends Animal {
public function makeSound() {
echo "$this->name says Meow!<br />";
}
}
// Create and use objects
$dog = new Dog("Benjy");
$dog->describe();
$dog->makeSound();
$cat = new Cat("Whiskers");
$cat->describe();
$cat->makeSound();
?>
Output:
Benjy is an animal.
Benjy says Woof!
Whiskers is an animal.
Whiskers says Meow!
In this example, both Dog and Cat inherit from the abstract class Animal. The makeSound() method behaves differently depending on the object type—this is polymorphism.
An interface is a special construct that contains only method declarations and no implementation. It acts as a rulebook that any implementing class must follow. When a class implements an interface, it must provide all the methods specified by that interface.
Key Differences from Abstract Classes
- Interfaces cannot have any method implementation (all methods are abstract by default).
- A class can implement multiple interfaces (but can extend only one class).
- Interfaces cannot have properties, only method declarations.
Worked Example: Payment Methods
<?php
// Define an interface
interface PaymentMethod {
public function pay($amount);
}
// CreditCard implements the interface
class CreditCard implements PaymentMethod {
public function pay($amount) {
echo "Pay TZS $amount using Credit Card.<br/>";
}
}
// PayPal implements the interface
class PayPal implements PaymentMethod {
public function pay($amount) {
echo "Pay TZS $amount using PayPal.<br/>";
}
}
// MobileMoney implements the interface
class MobileMoney implements PaymentMethod {
public function pay($amount) {
echo "Pay TZS $amount using M-Pesa.<br/>";
}
}
// Function that accepts any PaymentMethod
function processPayment(PaymentMethod $method, $amount) {
$method->pay($amount);
}
// Create objects
$method1 = new CreditCard();
$method2 = new PayPal();
$method3 = new MobileMoney();
// Process payments - polymorphism in action
processPayment($method1, 50000); // TZS 50,000
processPayment($method2, 25000); // TZS 25,000
processPayment($method3, 10000); // TZS 10,000
?>
Output:
Pay TZS 50000 using Credit Card.
Pay TZS 25000 using PayPal.
Pay TZS 10000 using M-Pesa.
The function processPayment() demonstrates polymorphism by accepting any object that implements the PaymentMethod interface and calling its pay() method, without needing to know the specific payment type.
| Feature | Abstract Class | Interface |
|---|---|---|
| Instantiation | Cannot be instantiated | Cannot be instantiated |
| Methods | Can have abstract and regular methods | Only method declarations |
| Properties | Can have properties | Cannot have properties |
| Inheritance | A class extends one abstract class | A class implements multiple interfaces |
Both abstract classes and interfaces allow you to achieve polymorphism by defining a common structure that different classes must follow, while allowing each class to implement the behaviour in its own way.
In Tanzania, mobile money services like M-Pesa, Airtel Money, and Tigo Pesa all work differently behind the scenes, but they all follow the same basic rule: they allow you to send and receive money. Using polymorphism, a banking app developer can write one function that works with any payment method—whether the user chooses M-Pesa, bank transfer, or cash—without needing to write separate code for each option. This makes the app faster to build and easier to maintain as new payment options are added.
Jinsi utakavyotathminiwaTathmini ya mchakato · Tathmini ya matokeo · Tathmini ya maarifa
Tathmini ya mchakato
The student should be able to:
- Define abstractclasses or interfaces and their associated methods.
- Implement methods in derived classes adhering to the interface.
Tathmini ya matokeo
Abstract classes and interfaces are correctly defined and implemented to exhibit polymorphism behaviour.
Tathmini ya maarifa
Methods used: The trainee should explain how to:
- Define and implement abstract classes or interfaces.
- Use polymorphism to invoke methods from derived classes
Principles: The student should explain the principle of:
- Polymorphism as a means to simplify complex systems through consistent interfaces.
- Abstraction and its role in achieving polymorphism using abstract classes and interfaces
Theories: The trainee should explain: The trainee should explain:
- How polymorphism enhances flexibility and extensibility.
- The role of abstract classes and interfaces in defining common behaviours
Circumstantial knowledge:
Detailed knowledge about:
- Common errors in implementing polymorphism and how to address them.
- Best practices for designing systems using abstract classes and interfaces
Swali
Which statement about abstract classes in PHP is correct?
Ingia ili kuwasilisha jibu lako na lihesabiwe katika umahiri wako.
Ingia ili kufanya mazoeziMwalimu
Umekwama? Niulize chochote kuhusu mada hii.
Ingia ili kumuuliza Mwalimu wa AI wa Sonza kuhusu swali hili.
Ingia ili kuulizaMajadiliano
Hakuna maswali bado