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: Applying Syntax and Constructs
Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around data and objects rather than functions and logic. This study note covers the essential syntax and constructs needed to create effective OOP programs using languages like C++, Java, or Python.
A class serves as a blueprint or template for creating objects. It defines the attributes (data) and methods (functions) that objects of that class will have. An object is an instance of a class—a concrete realization with actual values.
Key Definitions
- Class: A user-defined data type that acts as a blueprint for creating objects
- Object: An instance of a class with actual data stored in memory
- Attributes: Variables defined inside a class that represent the state of an object (also called fields or properties)
- Methods: Functions defined inside a class that describe the behaviors of an object
Syntax in C++
class Car {
public: // Access specifier
// Attributes (data members)
string make;
string model;
int year;
// Method (behavior)
void displayInfo() {
cout << "Car: " << year << " " << make << " " << model << endl;
}
};
int main() {
Car myCar; // Creating an object
myCar.make = "Toyota";
myCar.model = "Corolla";
myCar.year = 2022;
myCar.displayInfo();
return 0;
}
A constructor is a special method that is automatically called when an object is created. It initializes the object's attributes. A destructor is called when an object is destroyed to release resources.
Constructor Types
- Default Constructor: Takes no parameters
- Parameterized Constructor: Takes parameters to initialize attributes with specific values
class BankAccount {
private:
string accountHolder;
double balance;
public:
// Parameterized constructor
BankAccount(string name, double initialBalance) {
accountHolder = name;
balance = initialBalance;
}
// Destructor
~BankAccount() {
cout << "Account for " << accountHolder << " closed." << endl;
}
void display() {
cout << "Holder: " << accountHolder << ", Balance: TZS " << balance << endl;
}
};
int main() {
BankAccount acc("John Mwakidudu", 500000);
acc.display();
return 0;
}
Encapsulation bundles data (attributes) and methods that operate on that data into a single unit (class). It also restricts direct access to some components, which prevents accidental modification of data. Access specifiers control visibility:
- public: Accessible from anywhere
- private: Accessible only within the class (default for class members)
- protected: Accessible within the class and derived classes
class BankAccount {
private: // Private data - hidden from outside
string accountNumber;
double balance;
public: // Public methods - controlled access
// Constructor
BankAccount(string accNum, double bal) {
accountNumber = accNum;
balance = bal;
}
// Getter method
double getBalance() {
return balance;
}
// Setter method with validation
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
} else {
cout << "Insufficient funds!" << endl;
}
}
};

Inheritance allows a new class (subclass/derived class) to inherit attributes and methods from an existing class (superclass/base class). This promotes code reusability.
Types of Inheritance
- Single Inheritance: One subclass inherits from one superclass
- Multilevel Inheritance: A class inherits from another class, which itself inherits from another
- Hierarchical Inheritance: One superclass has multiple subclasses
- Hybrid Inheritance: Combination of multiple inheritance types
// Base class (Parent)
class Animal {
public:
string name;
int age;
void eat() {
cout << name << " is eating." << endl;
}
};
// Derived class (Child)
class Dog : public Animal {
public:
string breed;
void bark() {
cout << name << " barks: Woof! Woof!" << endl;
}
};
int main() {
Dog myDog;
myDog.name = "Bingo";
myDog.age = 3;
myDog.breed = "German Shepherd";
myDog.eat();
myDog.bark();
return 0;
}
Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables a single interface to represent different underlying forms.
Method Overloading (Compile-time Polymorphism)
Multiple methods with the same name but different parameters within the same class.
class Calculator {
public:
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;
}
};
Method Overriding (Runtime Polymorphism)
A subclass provides its own implementation of a method already defined in the superclass.
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(); // Polymorphic call
}
return 0;
}
Abstraction hides complex implementation details and shows only essential features. It focuses on what an object does rather than how it does it.
#include <iostream>
using namespace std;
class BankAccount {
private:
string accountNumber;
double balance;
public:
void deposit(double amount) {
// Implementation hidden from user
balance += amount;
cout << "Deposit successful!" << endl;
}
void withdraw(double amount) {
// User doesn't need to know internal logic
if (amount <= balance) {
balance -= amount;
cout << "Withdrawal successful!" << endl;
} else {
cout << "Insufficient balance!" << endl;
}
}
void displayBalance() {
cout << "Current balance: TZS " << balance << endl;
}
};
int main() {
BankAccount acc;
acc.deposit(100000);
acc.displayBalance();
acc.withdraw(30000);
acc.displayBalance();
return 0;
}
Arrays of Objects
class Student {
public:
string name;
int marks;
void display() {
cout << name << ": " << marks << endl;
}
};
int main() {
Student students[3];
students[0].name = "Amina";
students[0].marks = 85;
students[1].name = "Rajabu";
students[1].marks = 92;
students[2].name = "Grace";
students[2].marks = 78;
for (int i = 0; i < 3; i++) {
students[i].display();
}
return 0;
}
| Principle | Description |
|---|---|
| Encapsulation | Bundling data and methods into a single unit; restricting direct access to data |
| Inheritance | Mechanism where a class acquires properties of another class |
| Polymorphism | Ability of objects to take many forms; same method behaves differently |
| Abstraction | Hiding complex implementation details and showing only essential features |
Syntax Errors
- Missing semicolons, parentheses, or braces
- Misspelled keywords
- Case sensitivity issues
Semantic Errors
- Using uninitialized variables
- Type mismatches
- Incorrect operator usage
Logical Errors
- Wrong formula implementation
- Loop errors (off-by-one)
- Incorrect condition in if statements
Runtime Errors
- Division by zero
- Array index out of bounds
- Null pointer dereference
In Tanzania, OOP principles are widely used in mobile banking applications like M-Pesa and banking systems. For example, when developing a school fee payment system, a programmer would create a Student class with attributes like name, admission number, and balance, then use inheritance to create PrimaryStudent and SecondaryStudent subclasses. Encapsulation ensures that private data like account balances can only be modified through public methods like deposit() and withdraw(), preventing unauthorized access and maintaining data integrity for handling school fees in Tanzanian shillings.
Swali
What is the primary purpose of a constructor 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