Mada za sehemu hiiDemonstrate mastery of basic principles of Object Oriented Programming (Using C++; Java; Python; etc)Mada 4
- Describe the concept of Object Oriented Programming (Output, Directives, input, type bool, set width manipulator, type conversion, Object oriented paradigm differences between Object Oriented Programming and Procedure oriented programming, Encapsulation, Inheritance, composition and Polymorphism, Benefits of OOP, Structure of C++/Java/python, namespace, Data types, C++/Java/python tokens, Identifiers, Variables, Constants, Operators, Control structures and Loops)
- Describe the general structure of Object Oriented Program (Using C++, Java, Python, etc)
- Apply appropriate syntax and constructs to create Object Oriented programs
- Debug Object Oriented programs using appropriate skills (Use C++, Java, Python, etc)
Object Oriented Programming
Object-Oriented Programming (OOP) is a programming paradigm that models real-world entities as objects, which contain both data (called attributes or properties) and functions (called methods). This approach helps programmers organize code in a modular, reusable, and maintainable way.
In daily life, we naturally think in terms of objects. For example, a car is an object with properties like color, model, and speed, and behaviors like accelerate() and brake(). Similarly, OOP allows us to represent such real-world entities in our programs.
Key Terms
- Class: A blueprint or template for creating objects. It defines the attributes and methods that objects of that class will have.
- Object: An instance of a class. It represents a specific entity with its own unique data.
- Attributes (or Properties): Variables defined inside a class that represent the state or characteristics of an object.
- Methods: Functions defined inside a class that describe the behaviors or actions an object can perform.
Example: Class and Object
Consider a class called Car:
class Car {
public:
string make; // attribute
string model; // attribute
int year; // attribute
void startEngine() { // method
cout << "Engine started!";
}
};
To create an object from this class:
Car myCar; // creating an object
myCar.make = "Toyota";
myCar.model = "Corolla";
myCar.year = 2021;
myCar.startEngine(); // calling method
In this example, Car is the class (blueprint), while myCar is a specific object (instance) with its own data values.

OOP is built on four fundamental pillars:
1. Encapsulation
Encapsulation is the practice of bundling data (attributes) and methods that operate on that data within a single unit (class). It also involves data hiding — restricting direct access to some object's components to prevent unauthorized modification.
In encapsulation, attributes are typically declared as private, and access is provided through public getter and setter methods.
Example in C++
class BankAccount {
private: // data hiding - private attributes
string accountHolder;
double balance;
public:
// Setter method
void setBalance(double amount) {
if (amount >= 0)
balance = amount;
}
// Getter method
double getBalance() {
return balance;
}
};
Benefits of Encapsulation
- Data protection: Prevents unauthorized access to sensitive data
- Controlled modifications: Changes can be validated before applying
- Information hiding: Internal implementation details are hidden from users
- Flexibility: Internal changes don't affect how users interact with the object
2. Inheritance
Inheritance allows a new class (called subclass or derived class) to inherit attributes and methods from an existing class (called superclass or parent class). This promotes code reusability and establishes a hierarchical relationship between classes.
Types of Inheritance
| Type | Description |
|---|---|
| Single inheritance | A subclass inherits from one parent class |
| Multilevel inheritance | A class inherits from another class, which itself inherits from another (chain) |
| Hierarchical inheritance | One parent class has multiple child classes |
| Hybrid inheritance | Combination of multiple inheritance types |
Example in C++
// Parent class
class Animal {
public:
void eat() {
cout << "Animal is eating";
}
};
// Child class inheriting from Animal
class Dog : public Animal {
public:
void bark() {
cout << "Dog barks: Woof! Woof!";
}
};
int main() {
Dog myDog;
myDog.eat(); // inherited from Animal
myDog.bark(); // own method
return 0;
}
In this example, Dog is the subclass that inherits from Animal (superclass). The Dog object can use both its own method (bark) and the inherited method (eat).
3. Polymorphism
Polymorphism means "many forms." It allows objects from different classes to be treated as objects of a common superclass. It also enables a single method name to behave differently based on the object calling it.
Types of Polymorphism
| Type | Description |
|---|---|
| Compile-time (Static) Polymorphism | Method overloading - same method name with different parameters |
| Runtime (Dynamic) Polymorphism | Method overriding - subclass provides different implementation of parent method |
Method Overloading (Compile-time)
class Calculator {
public:
// Same method name, different parameters
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
};
int main() {
Calculator calc;
cout << calc.add(5, 3) << endl; // calls int version
cout << calc.add(2.5, 3.7) << endl; // calls double version
cout << calc.add(1, 2, 3) << endl; // calls three-parameter version
return 0;
}
Method Overriding (Runtime)
class Shape {
public:
virtual void draw() {
cout << "Drawing a shape" << endl;
}
};
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing a circle" << endl;
}
};
class Rectangle : public Shape {
public:
void draw() override {
cout << "Drawing a rectangle" << endl;
}
};
int main() {
Shape* shapes[2];
shapes[0] = new Circle();
shapes[1] = new Rectangle();
for (int i = 0; i < 2; i++) {
shapes[i]->draw(); // calls appropriate version at runtime
}
return 0;
}
4. Abstraction
Abstraction is the process of hiding complex implementation details and showing only the essential features of an object. It helps manage complexity by focusing on what an object does rather than how it does it.
Think of driving a car: you need to know how to steer, accelerate, and brake, but you don't need to understand how the engine's internal combustion works. The car's interface (steering wheel, pedals) provides abstraction.
Example in C++
class CoffeeMachine {
private:
// Hidden internal details
int temperature;
int waterLevel;
int grindSize;
public:
// Simple interface - user only sees this
void makeCoffee() {
// Complex internal operations hidden from user
heatWater();
grindBeans();
brew();
cout << "Coffee is ready!" << endl;
}
// Other methods user can call
void addWater() { waterLevel = 100; }
void addBeans() { }
};
In this example, the user simply calls makeCoffee() without needing to know the complex steps involved internally.
| Feature | POP (Procedure-Oriented) | OOP (Object-Oriented) |
|---|---|---|
| Program structure | Divided into functions | Divided into objects and classes |
| Focus | On functions and sequence of actions | On data (real-world modeling) |
| Approach | Top-down | Bottom-up |
| Access specifiers | Not available | public, private, protected |
| Data movement | Data flows freely between functions | Data encapsulated within objects |
| Adding new features | Difficult | Easier through inheritance |
| Data security | Less secure | More secure (data hiding) |
| Overloading | Not possible | Possible (function and operator overloading) |
| Examples | C, Pascal, FORTRAN | C++, Java, Python, C# |
- Code reusability: Inheritance allows reusing code from parent classes
- Modularity: Complex problems are broken into manageable objects
- Data security: Encapsulation protects sensitive information
- Easy maintenance: Changes to one object don't affect others
- Real-world modeling: Objects represent real-world entities naturally
- Scalability: Systems can grow easily by adding new classes
#include <iostream> // Preprocessor directive
using namespace std;
// Class definition
class MyClass {
private:
int data; // private attribute
public:
// Constructor
MyClass() {
data = 0;
}
// Setter
void setData(int value) {
data = value;
}
// Getter
int getData() {
return data;
}
};
int main() { // Main function
MyClass obj; // Creating object
obj.setData(10);
cout << "Data: " << obj.getData() << endl;
return 0;
}
Key C++ Elements
- #include
: Preprocessor directive to include input/output library - using namespace std: Allows using standard library names without prefix
- class: Keyword to define a class
- int main(): Entry point of every C++ program
- cout: Console output stream
- cin: Console input stream
C++ supports several data types:
| Category | Types |
|---|---|
| Integer | int, short, long, unsigned int |
| Floating-point | float, double, long double |
| Character | char, signed char, unsigned char |
| Boolean | bool (true or false) |
Variables
A variable is a named memory location that stores data which can change during program execution.
int age = 20; // integer variable
double price = 1500.50; // double variable
char grade = 'A'; // character variable
bool isStudent = true; // boolean variable
Constants
Constants are values that cannot be changed once defined:
const double PI = 3.14159;
const int MAX_STUDENTS = 100;
C++ supports various operators:
- Arithmetic: +, -, *, /, %
- Relational: <, >, <=, >=, ==, !=
- Logical: && (AND), || (OR), ! (NOT)
- Assignment: =, +=, -=, *=, /=
- Increment/Decrement: ++, --
Selection Statements
// If-else statement
if (marks >= 50) {
cout << "Pass" << endl;
} else {
cout << "Fail" << endl;
}
// Switch statement
switch (day) {
case 1: cout << "Monday"; break;
case 2: cout << "Tuesday"; break;
default: cout << "Invalid"; break;
}
Loop Statements
// For loop
for (int i = 0; i < 5; i++) {
cout << i << endl;
}
// While loop
while (count < 10) {
count++;
}
// Do-while loop
do {
cout << count << endl;
count++;
} while (count < 5);
In Tanzania, OOP principles are applied in developing banking systems such as those used by NMB and CRDB banks. For example, a BankAccount class encapsulates customer data (account number, balance) and provides controlled methods for deposits and withdrawals. Different account types like SavingsAccount and CheckingAccount can inherit from a base Account class, each adding their specific features like interest rates or overdraft limits. When you send money via mobile banking (such as M-Pesa), the system uses polymorphism to handle different transaction types—deposits, withdrawals, and transfers—through a common interface, ensuring your funds are processed securely and accurately.
Swali
What is a class 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 kuuliza