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
Designing Abstract Classes for Common Behaviour
In programming, you often have many different objects that do similar things but in different ways. For example, in a transport system, a Bus and a Taxi both need to move, but a bus carries many people and a taxi carries fewer. An abstract class lets you define the idea of "moving" in one place (the parent class) and lets each specific type of vehicle decide exactly how to "move" itself.
What is an Abstract Class?
An abstract class is a special kind of class in OOP that cannot be used to create objects directly. It acts as a blueprint or a template for other classes. Its job is to define common behaviour (methods) that all its child classes should have.
Think of it like a Miche (template) for making cakes. You have the shape of the cake, but you haven't decided if it is a chocolate cake or a fruit cake yet. The Miche defines the basic structure, and the actual cake (the child class) provides the specific details.
What is an Abstract Method?
Inside an abstract class, you can have abstract methods. An abstract method is a method that is declared but does not contain any code. It is just a rule that says: "Any class that inherits from me MUST have this method, and YOU must write the code for it."
For example, you can declare an abstract method called calculateArea() in an abstract class Shape. You don't write the code there because you don't know if the shape is a Circle or a Rectangle. You force the Circle class and the Rectangle class to write their own code for calculateArea().
How to Design an Abstract Class
- Declare the Class: Use the keyword
abstractbefore the wordclass. - Define Common Methods: You can write regular methods (with code) that all child classes will share.
- Define Abstract Methods: Use the keyword
abstractbefore the method name. Do not write curly braces{}or any code inside. - Create Child Classes: Use the keyword
extendsto inherit from the abstract class. - Implement Abstract Methods: In the child class, write the full code for the abstract methods.
Worked Example: Farm Animals (Mifugo)
Let's say we are building a program for a Tanzanian farm. All animals make a sound, but a Kuku (Chicken) makes a different sound from a Ng'ombe (Cow).
Step 1: Define the Abstract Class
We create an abstract class named Mifugo. It has one abstract method kupaSauti() (makeSound). Every animal must be able to make a sound.
<?php
// 1. Abstract class
abstract class Mifugo {
public $jina; // name
// Constructor
public function __construct($jinaLaMifugo) {
$this->jina = $jinaLaMifugo;
}
// 2. Abstract method - must be implemented by children
abstract public function kupaSauti();
// 3. Regular method - shared by all children
public function kueleza() {
echo "$this->jina ni mnyama mmoja wa mifugo.<br>";
}
}
?>
Step 2: Create Child Classes
Now we create the Kuku class. It must provide the code for kupaSauti().
class Kuku extends Mifugo {
// Implementing the abstract method
public function kupaSauti() {
echo "$this->jina anasema: Kokoo! Kokoo!<br>";
}
}
class Ng'ombe extends Mifugo {
// Implementing the abstract method
public function kupaSauti() {
echo "$this->jina anasema: Mmoo! Mmoo!<br>";
}
}
?>
Step 3: Using the Classes
We cannot create an object from Mifugo directly (e.g., $sasa = new Mifugo(); will fail). We create objects from the child classes.
// Create objects of specific animals
$kukuWangu = new Kuku("Kuku Mdogo");
$ng'ombeWangu = new Ng'ombe("Mbwa Mweusi"); // Wait, Mbwa is Dog. Let's use Ng'ombe.
// Note: $ng'ombeWangu is an object of type Ng'ombe,
// but it is also treated as type Mifugo because of inheritance.
// Using the methods
$kukuWangu->kueleza(); // Inherited method
$kukuWangu->kupaSauti(); // Implemented method
?>
Why Use Abstract Classes?
- Code Reuse: You write the common methods (like
kueleza) once in the parent class, and all children get them for free. - Consistency: They force every child class to have specific methods, ensuring your program is structured correctly.
- Polymorphism: You can write a function that accepts any object of type
Mifugo. You can pass aKukuor aNg'ombeto that function, and it will know how to callkupaSauti()correctly for each one.
Real-life application
In Tanzania, mobile money systems like M-Pesa or banking apps use abstract classes to handle payments. An abstract class like Malipo (Payment) might define a common method tumaMalipo(). The specific classes, such as MpesaPayment and BankPayment, inherit from this class and implement the method differently, ensuring that whether a user pays school fees or buys airtime, the system knows exactly what to do.
Jinsi utakavyotathminiwaTathmini ya mchakato · Tathmini ya matokeo · Tathmini ya maarifa
Tathmini ya mchakato
The student should be able to:
- Define abstract classes with appropriate attributes and methods for common behavior.
- Implementderived classes that inherit from abstract classes and provide specific functionality.
Tathmini ya matokeo
Abstract classes and their methods are logically designed to encapsulate shared behaviour.
Tathmini ya maarifa
Methods used: The trainee should explain how to:
- Design and define abstract classes for shared behaviors.
- Implement and override abstract methods in derived classes.
Principles: The student should explain the principle of:
- Abstraction and its role in enforcing consistent behaviours across multiple implementations.
- Code reusability through the use of abstract classes.
Theories: The trainee should explain: The trainee should explain:
- How abstract classes promote code organization and reduce duplication.
- The role of polymorphism in enabling objects to interact through common interfaces.
- The benefits of separating interface definitions from implementations
Circumstantial knowledge:
Detailed knowledge about:
- Best practices for designing abstract classes to maximize reusability
Swali
What is an abstract class in PHP?
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