Mada za sehemu hiiImplementing encapsulation and abstractionMada 2
- Implementing encapsulation of class attributes and methods
- Implementing abstraction of functionalities using abstract classes and method
Encapsulation is a way of bundling data (properties) and actions (methods) together inside a class while hiding the internal details from outside code. It protects data from being changed or accessed directly by accident. Think of a school report file kept in the staff room — not every student can open it and change their own marks. Only authorized teachers may view or update it using proper procedures. In programming, encapsulation works the same way: we hide the internal details of a class and provide special public methods to safely read or change the data.
Access modifiers are keywords that determine where and how different parts of the code can be accessed. They control the visibility of class properties and methods.
Public — When a property or method is public, it can be accessed from anywhere: inside the class, outside the class, and even in other files. Example: a method that displays a welcome message on the screen.
Private — When a property or method is private, it can only be accessed within the class where it is defined. Outside code cannot access it directly. Example: a person's password stored in a class should be private so no one can read it directly.
Protected — When a property or method is protected, it can be accessed inside the class and also by any class that inherits from it (its child classes). Example: a base class called Vehicle might have a protected method for starting the engine, which Car and Motorcycle classes can use.
The thiskeywordreferstothecurrentobject—theonethatisrunningthecodeatthatmoment.Itallowsanobjecttorefertoitself,itsownproperties,anditsownmethodswithintheclass.Forexample,this->name means "the name property of this object."
Since private properties cannot be accessed directly from outside the class, we use special methods called getters and setters to read and update them safely.
Getter — A getter method returns the value of a private or protected property. Example: getName() returns the student's name.
Setter — A setter method updates the value of a private or protected property, often with validation. Example: setAge($value) might only allow the age to be set if the number is positive.
The following PHP code demonstrates how to protect class attributes using private access modifiers and how to access them through getter and setter methods.
<?php
class Student {
// Public property: accessible from anywhere
public $schoolName = "Green Valley School";
// Private properties: accessible only within this class
private $name;
private $age;
// Protected property: accessible in this class and its child classes
protected $grade;
// Constructor sets initial values
public function __construct($studentName, $studentAge, $studentGrade) {
$this->name = $studentName;
$this->age = $studentAge;
$this->grade = $studentGrade;
}
// Getter for name
public function getName() {
return $this->name;
}
// Setter for name
public function setName($newName) {
$this->name = $newName;
}
// Getter for age
public function getAge() {
return $this->age;
}
// Setter for age with validation
public function setAge($newAge) {
if ($newAge > 0) {
$this->age = $newAge;
} else {
echo "Invalid age value!";
}
}
// Method to display student information
public function displayInfo() {
echo "Student: {$this->name}, Age: {$this->age}, Grade: {$this->grade}";
}
}
// Create a new Student object
$studObj = new Student("Amina", 15, "Form Two");
// Accessing a public property directly
echo "School: " . $studObj->schoolName . "\n";
// Accessing private data using getter methods
echo "Name: " . $studObj->getName() . "\n";
echo "Age: " . $studObj->getAge() . "\n";
// Updating private data using setter methods
$studObj->setName("Amina Yusuf");
$studObj->setAge(16);
// Display full student info
$studObj->displayInfo();
?>
In this example:
- $schoolName is public — anyone can access it directly.
- nameandage are private — they can only be read or changed using the getter and setter methods.
- $grade is protected — it can be used inside the class and by any child class.
- The setAge() method validates that the age is a positive number before updating it.
Encapsulation is widely used in mobile money applications in Tanzania, such as M-Pesa or Tigo Pesa. When a user deposits or withdraws money, the account balance is kept private — no outside code can change it directly. Instead, the application uses controlled methods (setters with validation) to update the balance, ensuring that the amount is valid and that transactions are secure. This protects users from errors and fraud, just as encapsulation protects programs from accidental data corruption.
Jinsi utakavyotathminiwaTathmini ya mchakato · Tathmini ya matokeo · Tathmini ya maarifa
Tathmini ya mchakato
The student should be able to:
- Apply appropriate accessmodifiers to class attributes and methods.
- Use getter and setter methods to manage attribute access and updates.
- Implement encapsulation to enhance data security
Tathmini ya matokeo
Attributes and methods are correctly encapsulated using access modifiers.
Tathmini ya maarifa
Methods used: The trainee should explain how to:
- Encapsulate class attributes and methods using appropriate access modifiers.
- Use getter and setter methods to provide controlled access to class attributes.
Principles: The student should explain the principle of:
- Encapsulation as a means to protect data and reduce dependency between components.
- Data hiding and the separation of implementation from interface.
Theories: The trainee should explain: The trainee should explain:
- How encapsulation improves code security and maintainability.
- The importance of access modifiers in implementing encapsulation.
- The role of getter and setter methods in managing data access.
Circumstantial knowledge:
Detailed knowledge about:
- Common mistakes in encapsulation and how to avoid them.
- Best practices for designing encapsulated classes in real-world applications.
Swali
What is the main purpose of encapsulation in object-oriented programming?
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