Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← Fundamentals of Object Oriented Programming · Lesson 2 of 6

Module One

📖 Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
1

Course Outline

CS 201 · Fundamentals of Object-Oriented Programming

Fundamentals of Object-Oriented Programming

CS 201 · Core Course · 15 Weeks
Credits3 (2 Lec + 1 Lab)
PrerequisiteIntro to Programming
LanguageJava / C++ / Python
DeliveryLectures + Labs

Course Description

This course introduces the core principles of object-oriented programming (OOP). Students will learn to design and implement software using classes, objects, encapsulation, inheritance, polymorphism, and abstraction. Emphasis is placed on problem-solving, code reusability, and building maintainable applications.

Learning Outcomes

  • Explain procedural vs. object-oriented paradigms
  • Design classes and create objects with attributes and methods
  • Apply encapsulation, inheritance, polymorphism, abstraction
  • Use UML diagrams to model object-oriented designs
  • Implement exception handling and basic file I/O
  • Develop a complete OOP-based application

Weekly Schedule

Week Topic Details / Lab
1 Intro to Programming Paradigms Procedural vs. OOP · benefits · real-world applications · toolchain overview
2 Classes and Objects Defining classes · attributes & methods · constructors / destructors · this/self
3 Encapsulation Access modifiers · getters/setters · data hiding · class vs. instance members
4 Methods in Depth Lab Method overloading · parameter passing · static methods · Lab: BankAccount class
5 Inheritance (Part 1) Base/derived classes · extends · constructor chaining (super) · method overriding
6 Inheritance (Part 2) Lab Types of inheritance · abstract classes · final/sealed · Lab: Employee hierarchy (Manager, Developer, Intern)
7 Polymorphism Midterm Compile-time vs. runtime · dynamic dispatch · upcasting/downcasting · Midterm Exam
8 Interfaces & Abstract Classes Lab Defining/implementing interfaces · multiple inheritance via interfaces · trade-offs · Lab: Shape interface (Circle, Rectangle, Triangle)
9 Association, Aggregation, Composition "Has-a" vs. "Is-a" · dependency & coupling · real-world models (Library → Book)
10 Exception Handling Types of errors · try-catch-finally · custom exceptions · best practices
11 Generics and Collections Generic classes/methods · List, Set, Map · iterating over collections
12 File I/O & Persistence Lab Reading/writing files · serialization concepts · Lab: Save/load objects to file
13 UML and Design Principles Class & sequence diagrams · SOLID intro · refactoring poorly designed code
14 Design Patterns (Introduction) Singleton · Factory · Observer · when/why to use patterns · Project Workshop
15 Course Project & Review Final Final project presentations · code reviews · Final Exam

Assessment Breakdown

25%
Assignments & Labs
10%
Quizzes
20%
Midterm Exam
25%
Final Project
20%
Final Exam

Textbooks & Tools

Required Textbook

  • Object-Oriented Programming in [Language] by [Author]

Recommended

  • Head First Object-Oriented Analysis and Design by McLaughlin & Pollice

Tools

IntelliJ IDEA Eclipse Visual Studio PyCharm Git & GitHub draw.io / Lucidchart
2

Module One

Module One · Object Oriented Programming

📘 Module One: Getting Started with Object Oriented Programming

🌟 Module Introduction

Hello, future programmer! Have you ever wondered how video games create characters? How does a game know that a car has wheels, a colour, and can move? How does a banking app know that a customer has a name, an account number, and a balance? The answer is something called Object Oriented Programming, or OOP for short.

OOP is a way of writing computer programs. Instead of writing a long list of instructions, you build your program out of objects. An object is like a small machine that has its own data and its own actions. You can create many objects from the same blueprint. Each object can be different, but they all work the same way.

In this module, you will learn the very basics of OOP. You will learn what objects are, what classes are, and why they are useful. We will use simple words and many examples. By the end, you will understand how programmers think when they use OOP. Let’s begin!

🎯 Learning Objectives

After you finish this module, you will be able to:

  • Explain what programming is in simple words.
  • Describe what Object Oriented Programming means.
  • Explain what an object is.
  • Explain what a class is.
  • Understand the difference between a class and an object.
  • Identify attributes (data) of an object.
  • Identify methods (actions) of an object.
  • Create a simple class in your mind.
  • Create a simple object in your mind.
  • Understand why OOP helps programmers.
  • Avoid common mistakes when learning OOP.
  • Feel excited to continue learning about programming!

📖 Warm-up Story: Chidi and the Magic Toy Factory

Chidi lived in Aba. His uncle owned a toy factory. One day, Chidi visited the factory. He saw something amazing. There was a big machine that made toy cars. The machine had a blueprint. Every time the machine ran, it made a new toy car. Each car was the same shape, but they were painted different colours.

Chidi asked his uncle, “How does the machine know what a car looks like?” His uncle smiled and showed him a large paper. On the paper was a drawing of a car. It showed that a car has four wheels, a body, and a roof. It also showed that a car can move forward and backward.

“This paper is the blueprint,” said his uncle. “The machine uses this blueprint to make as many cars as we want. Each car is an object. The blueprint is the class.”

Chidi was confused. “What do you mean by object and class?” he asked. His uncle picked up two toy cars. “These two cars are objects,” he said. “They were made from the same blueprint. But this one is red and that one is blue. They have different colours, but they both have four wheels and can move.”

Chidi understood. “So the blueprint is the class,” he said. “And each car is an object.” His uncle nodded. “That is exactly what Object Oriented Programming is. You write a class once. Then you can create many objects from it.”

Moral of the story: A class is a blueprint. An object is a thing made from that blueprint. You can make many objects from one class.

📚 Main Lessons

Lesson 1: What is Programming?

Definition: Programming is writing instructions for a computer to follow.

Why it is important: Computers cannot think for themselves. They need step-by-step instructions.

Simple explanation: Imagine you are telling a robot how to make a sandwich. You say: “Pick up the bread. Put butter on it. Put cheese on it. Close the bread.” That is programming.

Real-life example: A washing machine follows a program. You choose “Quick Wash” and it follows steps.

School example: A recipe for baking a cake is like a program. It has steps to follow.

Home example: Your morning routine is a program. You wake up, brush your teeth, eat breakfast, go to school.

Nigerian example: A recipe for jollof rice is a program. It tells you what to do step by step.

Illustration:

  Start
    |
    V
  Step 1: Wake up
    |
    V
  Step 2: Brush teeth
    |
    V
  Step 3: Eat breakfast
    |
    V
  Step 4: Go to school
    |
    V
  End
  

Mini summary: Programming is writing instructions for a computer. A program is a list of steps.

Lesson 2: What is Object Oriented Programming?

Definition: Object Oriented Programming (OOP) is a way of writing programs using objects.

Why it is important: OOP helps programmers organise their code. It makes programs easier to build, fix, and change.

Simple explanation: Instead of writing one long list of instructions, you create small building blocks called objects. Each object has its own data and its own actions.

Real-life example: A car is an object. It has data (colour, speed) and actions (drive, stop).

School example: A student is an object. They have data (name, age) and actions (study, play).

Home example: A dog is an object. It has data (name, breed) and actions (bark, run).

Nigerian example: A trader in the market is an object. They have data (name, goods) and actions (buy, sell).

Illustration:

  +---------------------+
  |  OBJECT: Car        |
  |  Data: colour, speed|
  |  Actions: drive, stop|
  +---------------------+
  

Mini summary: OOP uses objects. An object has data and actions. OOP makes programs easier to organise.

Lesson 3: What is an Object?

Definition: An object is a thing that has data and actions.

Why it is important: Objects are the building blocks of OOP. Everything in OOP is an object.

Simple explanation: Think of a phone. It has data (brand, colour, battery level) and actions (call, text, take photo). That is an object.

Real-life example: A football is an object. It has data (size, colour) and actions (bounce, roll).

School example: A book is an object. It has data (title, author, pages) and actions (open, close, read).

Home example: A fridge is an object. It has data (temperature, contents) and actions (cool, freeze).

Nigerian example: A danfo bus is an object. It has data (colour, route) and actions (move, stop).

Illustration:

  +---------------------+
  |  OBJECT: Phone      |
  |  Data: brand, colour|
  |  Actions: call, text|
  +---------------------+
  

Mini summary: An object is a thing with data and actions. Everything in OOP is an object.

Lesson 4: What is a Class?

Definition: A class is a blueprint for creating objects.

Why it is important: A class defines what data and actions an object will have.

Simple explanation: Think of a class as a cookie cutter. The cookie cutter is the class. The cookies are the objects. You can make many cookies from one cutter.

Real-life example: A house plan is a class. The houses built from it are objects.

School example: A uniform design is a class. Each student’s uniform is an object.

Home example: A recipe is a class. Each cake you bake is an object.

Nigerian example: A pattern for a dress is a class. Each dress sewn from it is an object.

Illustration:

  Class: "Car"
     |
     V
  +--------+ +--------+ +--------+
  | Car 1  | | Car 2  | | Car 3  |
  | Red    | | Blue   | | Green  |
  +--------+ +--------+ +--------+
  Objects made from the class
  

Mini summary: A class is a blueprint. It defines what objects will look like.

Lesson 5: Class vs Object – What is the Difference?

Definition: A class is the blueprint. An object is the thing made from the blueprint.

Why it is important: This is the most important idea in OOP. If you understand this, you understand OOP.

Simple explanation: A class is like a plan for a house. An object is an actual house you can live in.

Real-life example: A car factory has a design for a car (class). The cars that roll off the line are objects.

School example: A teacher’s lesson plan is a class. Each lesson taught is an object.

Home example: A recipe for bread is a class. Each loaf you bake is an object.

Nigerian example: A design for ankara fabric is a class. Each piece of fabric is an object.

Table: Class vs Object

FeatureClassObject
What is it?A blueprintA thing made from the blueprint
How many?One classMany objects
ExampleCar designYour red car
Exists in memory?NoYes

Illustration:

  Class (Blueprint)
       |
       V
  +---------+ +---------+ +---------+
  | Object 1| | Object 2| | Object 3|
  +---------+ +---------+ +---------+
  

Mini summary: A class is a blueprint. An object is a thing made from the blueprint. One class can make many objects.

Lesson 6: Attributes – The Data of an Object

Definition: Attributes are the data that an object holds. They describe what the object is like.

Why it is important: Attributes store information about an object.

Simple explanation: If the object is a student, the attributes are name, age, and class.

Real-life example: A phone has attributes: brand, colour, battery level.

School example: A student has attributes: name, age, grade.

Home example: A dog has attributes: name, breed, age.

Nigerian example: A market stall has attributes: owner name, goods sold, location.

Illustration:

  +---------------------+
  |  OBJECT: Student    |
  |  Attributes:        |
  |  - name: "Ada"      |
  |  - age: 14          |
  |  - grade: "JSS3"    |
  +---------------------+
  

Mini summary: Attributes are the data of an object. They describe what the object is like.

Lesson 7: Methods – The Actions of an Object

Definition: Methods are the actions that an object can do.

Why it is important: Methods let objects do things. They make objects useful.

Simple explanation: If the object is a student, the methods are study, play, and sleep.

Real-life example: A phone has methods: call, text, take photo.

School example: A student has methods: study, write, read.

Home example: A dog has methods: bark, run, eat.

Nigerian example: A trader has methods: buy, sell, count money.

Illustration:

  +---------------------+
  |  OBJECT: Student    |
  |  Methods:           |
  |  - study()          |
  |  - play()           |
  |  - sleep()          |
  +---------------------+
  

Mini summary: Methods are the actions of an object. They let objects do things.

Lesson 8: Attributes and Methods Together

Definition: An object has both attributes (data) and methods (actions).

Why it is important: This is what makes an object complete.

Simple explanation: Think of a car. Attributes: colour, speed. Methods: drive, stop.

Real-life example: A bank account has attributes: account number, balance. Methods: deposit, withdraw.

School example: A student has attributes: name, age. Methods: study, take exam.

Home example: A fridge has attributes: temperature. Methods: cool, defrost.

Nigerian example: A danfo bus has attributes: route, fare. Methods: pick passengers, drop passengers.

Illustration:

  +---------------------+
  |  OBJECT: Car        |
  |  Attributes:        |
  |  - colour: "red"    |
  |  - speed: 60        |
  |  Methods:           |
  |  - drive()          |
  |  - stop()           |
  +---------------------+
  

Mini summary: An object has both attributes and methods. Attributes are data. Methods are actions.

Lesson 9: Creating a Class in Your Mind

Definition: Creating a class means deciding what attributes and methods the objects will have.

Why it is important: You need to plan before you write code.

Simple explanation: Think of a class called “Student”. What data does a student have? Name, age, grade. What can a student do? Study, play, sleep.

Real-life example: A class called “Phone”. Attributes: brand, colour. Methods: call, text.

School example: A class called “Teacher”. Attributes: name, subject. Methods: teach, mark.

Home example: A class called “Pet”. Attributes: name, type. Methods: eat, sleep.

Nigerian example: A class called “Trader”. Attributes: name, goods. Methods: buy, sell.

Illustration:

  Class: Student
     |
     V
  Attributes: name, age, grade
  Methods: study, play, sleep
  

Mini summary: Creating a class means deciding its attributes and methods.

Lesson 10: Creating an Object in Your Mind

Definition: Creating an object means making a specific thing from a class.

Why it is important: Objects are what you use in your program.

Simple explanation: From the class “Student”, you create an object called “Ada”. Ada has name = “Ada”, age = 14, grade = “JSS3”.

Real-life example: From the class “Phone”, you create an object called “MyPhone”. It has brand = “Samsung”, colour = “blue”.

School example: From the class “Teacher”, you create an object called “MrBello”. He has subject = “Maths”.

Home example: From the class “Pet”, you create an object called “Bingo”. It has type = “dog”.

Nigerian example: From the class “Trader”, you create an object called “MamaNkechi”. She sells = “vegetables”.

Illustration:

  Class: Student
       |
       V
  Object: Ada
  name = "Ada"
  age = 14
  grade = "JSS3"
  

Mini summary: Creating an object means making a specific thing from a class. You fill in the data.

Lesson 11: Why OOP is Useful

Definition: OOP is useful because it helps organise code.

Why it is important: Organised code is easier to write, fix, and change.

Simple explanation: Imagine building a house with Lego blocks. Each block is an object. You can build anything by combining blocks. OOP is like Lego for programmers.

Real-life example: A car is made of many objects: engine, wheels, doors. Each object works on its own.

School example: A school is made of many objects: students, teachers, classrooms.

Home example: A kitchen is made of many objects: fridge, cooker, sink.

Nigerian example: A market is made of many objects: stalls, traders, customers.

Illustration:

  +-------+ +-------+ +-------+
  |Object | |Object | |Object |
  +-------+ +-------+ +-------+
       \       |       /
        \      |      /
         V     V     V
     +-----------------+
     |  BIG PROGRAM    |
     +-----------------+
  

Mini summary: OOP is useful because it organises code. It makes programs easier to build and fix.

Lesson 12: OOP in the Real World

Definition: OOP is used in many real-world programs.

Why it is important: Knowing where OOP is used helps you understand why you are learning it.

Simple explanation: Video games use OOP. Banking apps use OOP. Social media uses OOP.

Real-life example: In a game, each character is an object. Each has health, speed, and actions.

School example: A school management system uses objects for students, teachers, and classes.

Home example: A smart home app uses objects for lights, fans, and doors.

Nigerian example: A bank app uses objects for customers, accounts, and transactions.

Illustration:

  Video Game
      |
      V
  +--------+ +--------+ +--------+
  | Hero   | | Enemy  | | Weapon |
  | health | | health | | damage |
  | attack | | attack | | use    |
  +--------+ +--------+ +--------+
  

Mini summary: OOP is used in games, banking, social media, and many other programs.

Lesson 13: OOP vs Other Ways of Programming

Definition: There are other ways to program. OOP is one way.

Why it is important: Knowing the difference helps you understand why OOP is special.

Simple explanation: In older ways, you wrote a long list of steps. In OOP, you build objects that work together.

Real-life example: Old way: a recipe that says “do this, then this, then this”. OOP way: a team of chefs, each with their own job.

School example: Old way: one student does all the work. OOP way: a group project where each student has a role.

Home example: Old way: one person cooks everything. OOP way: family members each cook a dish.

Nigerian example: Old way: one trader sells everything. OOP way: a market with different stalls for different goods.

Table: OOP vs Procedural Programming

FeatureProceduralOOP
OrganisationStepsObjects
ReuseHardEasy
Fixing bugsHardEasier
Best forSimple tasksBig programs

Mini summary: OOP uses objects. Procedural uses steps. OOP is better for big programs.

Lesson 14: Thinking in Objects

Definition: Thinking in objects means looking at the world as a set of objects.

Why it is important: This is the first step to becoming an OOP programmer.

Simple explanation: When you see a car, think: what data does it have? What actions can it do?

Real-life example: When you see a phone, think: attributes (brand, colour), methods (call, text).

School example: When you see a student, think: attributes (name, age), methods (study, play).

Home example: When you see a dog, think: attributes (name, breed), methods (bark, run).

Nigerian example: When you see a danfo bus, think: attributes (route, fare), methods (move, stop).

Illustration:

  See a thing
       |
       V
  What data does it have? (Attributes)
       |
       V
  What can it do? (Methods)
       |
       V
  You are thinking in objects!
  

Mini summary: Thinking in objects means looking at things as having data and actions.

Lesson 15: Your First Steps – Review and Celebrate

Definition: You have learned the basics of OOP.

Why it is important: Reviewing helps you remember.

Simple explanation: You learned what programming is, what OOP is, what objects and classes are, and how to think in objects.

Real-life example: Like finishing the first chapter of a book.

School example: Like finishing the first week of a new class.

Home example: Like learning to ride a bicycle for the first time.

Nigerian example: Like learning to make jollof rice for the first time.

Illustration:

  Start → Learn Programming → Learn OOP → Learn Objects → Learn Classes → Ready for Module 2! 🎉
  

Mini summary: You know the basics of OOP. You are ready for Module Two.

📖 Key Vocabulary

WordSimple Definition
ProgrammingWriting instructions for a computer.
Object Oriented ProgrammingA way of programming using objects.
ObjectA thing with data and actions.
ClassA blueprint for creating objects.
AttributeData that an object holds.
MethodAn action that an object can do.
BlueprintA plan or design.
InstanceAnother word for an object made from a class.
ProceduralAn older way of programming using steps.
ReuseUsing something again.
OrganiseTo arrange things neatly.

🔑 Important Concepts

  • Programming is instructions: Computers follow steps.
  • OOP uses objects: Objects have data and actions.
  • Class is a blueprint: It defines what objects look like.
  • Object is a thing: It is made from a class.
  • Attributes are data: They describe the object.
  • Methods are actions: They let the object do things.
  • One class, many objects: You can create many objects from one class.
  • OOP organises code: It makes programs easier to build and fix.

🧭 Step-by-Step Explanations

How to think of a class

  1. Choose a thing (e.g., a student).
  2. List its attributes (name, age, grade).
  3. List its methods (study, play, sleep).
  4. You have created a class in your mind.

How to think of an object

  1. Start with a class (e.g., Student).
  2. Give it specific data (name = “Ada”, age = 14).
  3. You have created an object.

How to think in objects

  1. Look at a thing.
  2. Ask: what data does it have?
  3. Ask: what can it do?
  4. You are thinking in objects.

🌍 Real-life Examples

  • A car is an object. It has attributes (colour, speed) and methods (drive, stop).
  • A phone is an object. It has attributes (brand, colour) and methods (call, text).
  • A bank account is an object. It has attributes (balance) and methods (deposit, withdraw).
  • A student is an object. It has attributes (name, age) and methods (study, play).
  • A dog is an object. It has attributes (name, breed) and methods (bark, run).

🇳🇬 Nigerian Examples

  • A danfo bus is an object. It has attributes (route, fare) and methods (move, stop).
  • A market stall is an object. It has attributes (owner, goods) and methods (buy, sell).
  • A trader is an object. It has attributes (name, goods) and methods (buy, sell).
  • A student is an object. It has attributes (name, class) and methods (study, play).
  • A bank account is an object. It has attributes (balance) and methods (deposit, withdraw).

🎈 Fun Examples Children Can Relate To

  • A video game character is an object. It has health and can attack.
  • A football is an object. It has size and can bounce.
  • A favourite toy is an object. It has a colour and can make sounds.
  • A pet is an object. It has a name and can run.
  • A bicycle is an object. It has wheels and can move.

🏠 Everyday Examples

  • Your phone is an object. It has data and actions.
  • Your school bag is an object. It has data and actions.
  • Your fridge is an object. It has data and actions.
  • Your television is an object. It has data and actions.
  • Your watch is an object. It has data and actions.

👨‍👩‍👧 Parent Tips

  • Encourage your child to think of everyday things as objects.
  • Ask them to list attributes and methods of things at home.
  • Play a game: “What data does this have? What can it do?”
  • Celebrate when they understand the difference between a class and an object.
  • Remind them that programming is like building with blocks.

💡 Interesting Facts

  • OOP was invented in the 1960s.
  • The first OOP language was Simula.
  • Java and Python are popular OOP languages.
  • Almost all modern apps use OOP.
  • OOP makes it easier to work in teams.

🤔 Did You Know?

  • Did you know that a class can have no objects?
  • Did you know that one class can make thousands of objects?
  • Did you know that objects can have other objects inside them?
  • Did you know that OOP is used in video games like Minecraft?
  • Did you know that you can think in objects even without a computer?

📌 Remember This

  • Programming is writing instructions.
  • OOP uses objects.
  • An object has data and actions.
  • A class is a blueprint.
  • An object is a thing made from a class.
  • Attributes are data. Methods are actions.
  • One class can make many objects.
  • OOP organises code.

⚠️ Common Mistakes

  • Confusing a class with an object.
  • Thinking an object is the same as a class.
  • Forgetting that objects have both data and actions.
  • Thinking OOP is only for experts.
  • Not practising thinking in objects.

✅ Best Practices

  • Always ask: what data does this have?
  • Always ask: what can this do?
  • Start with simple objects.
  • Practise thinking in objects every day.
  • Remember: class is blueprint, object is thing.
  • Keep your code organised.

📊 Illustrations, Diagrams, and Tables

Flowchart: From Class to Object

  Class (Blueprint)
        |
        V
  Create Object
        |
        V
  Fill in Attributes
        |
        V
  Use Methods
        |
        V
  Object Works! 🎉
  

Timeline: History of OOP

  1960s - Simula, first OOP language
  1970s - Smalltalk
  1980s - C++
  1990s - Java
  2000s - Python, C#
  2024 - You learn OOP!
  

Table: Class vs Object

FeatureClassObject
What is it?A blueprintA thing made from the blueprint
How many?One classMany objects
ExampleCar designYour red car
Exists in memory?NoYes

Table: Attributes vs Methods

FeatureAttributesMethods
What are they?DataActions
Example (Student)name, agestudy, play
Example (Car)colour, speeddrive, stop

📝 Summary After Every Lesson

Lesson 1: Programming is writing instructions for a computer.

Lesson 2: OOP is a way of programming using objects.

Lesson 3: An object is a thing with data and actions.

Lesson 4: A class is a blueprint for creating objects.

Lesson 5: A class is a blueprint. An object is a thing made from the blueprint.

Lesson 6: Attributes are the data of an object.

Lesson 7: Methods are the actions of an object.

Lesson 8: An object has both attributes and methods.

Lesson 9: Creating a class means deciding its attributes and methods.

Lesson 10: Creating an object means making a specific thing from a class.

Lesson 11: OOP is useful because it organises code.

Lesson 12: OOP is used in games, banking, and social media.

Lesson 13: OOP uses objects. Procedural uses steps.

Lesson 14: Thinking in objects means looking at things as having data and actions.

Lesson 15: You reviewed and are ready for Module Two.

📦 End-of-Module Summary

In this module, you learned what programming is and what Object Oriented Programming means. You discovered that an object is a thing with data and actions. You learned that a class is a blueprint for creating objects. You learned about attributes (data) and methods (actions). You learned the difference between a class and an object. You learned why OOP is useful and where it is used. You also learned to think in objects. You are now ready for Module Two, where you will learn how to create classes and objects in code.

❓ Frequently Asked Questions (10 questions)

  1. What is programming? Writing instructions for a computer.
  2. What is OOP? A way of programming using objects.
  3. What is an object? A thing with data and actions.
  4. What is a class? A blueprint for creating objects.
  5. What is an attribute? Data that an object holds.
  6. What is a method? An action that an object can do.
  7. What is the difference between a class and an object? A class is a blueprint. An object is a thing made from the blueprint.
  8. How many objects can a class make? Many.
  9. Why is OOP useful? It organises code.
  10. Where is OOP used? In games, banking, social media, and many other programs.

🔗 Matching Exercises

Match the word to its meaning.

WordMeaning
1. ObjectA. Data that an object holds
2. ClassB. A thing with data and actions
3. AttributeC. An action that an object can do
4. MethodD. A blueprint for creating objects
5. OOPE. A way of programming using objects

Answers: 1-B, 2-D, 3-A, 4-C, 5-E

🧩 Scenario-based Exercises

  1. You want to create a program about cars. What is the class? (Car)
  2. You create a red car and a blue car. What are these? (Objects)
  3. The car has a colour and speed. What are these? (Attributes)
  4. The car can drive and stop. What are these? (Methods)
  5. You want to make 100 cars. How many classes do you need? (One)

👥 Group Activity

Title: Think in Objects

Instructions: In groups of 3, choose a thing (e.g., a phone, a student, a dog, a bus). List its attributes and methods. Present to the class. Discuss: what data does it have? What can it do?

🧑 Individual Activity

Title: My First Class in My Mind

Instructions: Think of a class called “MyPet”. Write down three attributes and three methods. Then create two objects from the class. Give each object different data. Write down what you created.

🛠️ Mini Project

Title: Design a Class for Your School

Instructions: Choose something in your school (e.g., Student, Teacher, Classroom). Write down its attributes and methods. Create three objects from the class. Give each object different data. Present your design to the class.

📋 Practical Assignment

Task: Write a short paragraph (5 sentences) explaining what you learned about OOP. Then, list three things you found easy and one thing you found hard. Finally, describe one class and one object you created in your mind.

🔑 Key Takeaways

  • Programming is writing instructions.
  • OOP uses objects.
  • An object has data and actions.
  • A class is a blueprint.
  • An object is a thing made from a class.
  • Attributes are data. Methods are actions.
  • One class can make many objects.
  • OOP organises code.
  • Thinking in objects is the first step.

💬 Classroom Discussion Questions

  1. Why is OOP useful for big programs?
  2. What is the difference between a class and an object?
  3. Can you think of an object in your home? What are its attributes and methods?
  4. Why do programmers use blueprints (classes)?
  5. What would you like to build with OOP?

➡️ Preparation for the Next Module

In Module Two, we will learn about creating classes and objects in code. You will write your first class. You will create objects from it. You will use attributes and methods. To get ready, make sure you:

  • Understand the difference between a class and an object.
  • Know what attributes and methods are.
  • Have practised thinking in objects.
  • Are ready to write some simple code.

See you in Module Two! 🚀


End of Module One · Object Oriented Programming

3

Module Two

Module Two · Object Oriented Programming

📘 Module Two: Creating Classes and Objects in Code

🌟 Module Introduction

Welcome back, future programmer! In Module One, you learned what Object Oriented Programming is. You learned that an object is a thing with data and actions. You learned that a class is a blueprint for creating objects. You also learned how to think in objects.

Now it is time to write real code. In this module, you will learn how to create a class in code. You will learn how to create objects from that class. You will learn how to give objects their own data. You will learn how to make objects do things using methods.

We will use a simple programming language called Python. Python is easy to read and write. It is used by millions of people around the world. Do not worry if you have never written code before. We will go step by step.

By the end of this module, you will have written your own class and created your own objects. You will see your code come to life. Let’s start coding!

🎯 Learning Objectives

After you finish this module, you will be able to:

  • Explain what Python is and why it is good for beginners.
  • Write a simple class in Python.
  • Use the __init__ method to set up attributes.
  • Create objects from a class.
  • Give each object its own data.
  • Write methods inside a class.
  • Call methods on an object.
  • Understand the self keyword.
  • Create multiple objects from one class.
  • Use objects in a simple program.
  • Avoid common mistakes when writing classes.
  • Feel confident to write your own classes.

📖 Warm-up Story: Ada and the Robot Factory

Ada lived in Lagos. Her uncle worked in a robot factory. One day, Ada visited the factory. She saw a big machine that made robots. The machine had a computer. On the computer was a program written in Python.

Ada asked her uncle, “How does the computer know how to make a robot?” Her uncle showed her the code. It looked like this:

  class Robot:
      def __init__(self, name, colour):
          self.name = name
          self.colour = colour

      def say_hello(self):
          print("Hello, my name is " + self.name)
  

“This is a class,” said her uncle. “It is a blueprint for making robots. The __init__ method sets up the robot’s name and colour. The say_hello method makes the robot speak.”

Ada was curious. “Can you make a robot for me?” she asked. Her uncle typed:

  my_robot = Robot("AdaBot", "blue")
  my_robot.say_hello()
  

The computer printed: Hello, my name is AdaBot. Ada was amazed. “So my_robot is an object,” she said. “And it was made from the class Robot.”

“Exactly!” said her uncle. “You can make as many robots as you want. Each one can have a different name and colour.”

Ada decided that day that she would learn to write classes and create objects. And that is exactly what you will do in this module.

Moral of the story: A class is a blueprint. An object is a thing made from the blueprint. You can make many objects from one class.

📚 Main Lessons

Lesson 1: What is Python?

Definition: Python is a programming language. It is a way to tell a computer what to do.

Why it is important: Python is easy to read and write. It is great for beginners.

Simple explanation: Python looks almost like English. You write instructions, and the computer follows them.

Real-life example: Many apps and websites are built with Python.

School example: Python is used in schools to teach programming.

Home example: You can use Python to make a simple calculator.

Nigerian example: Nigerian tech companies use Python to build software.

Illustration:

  +---------------------+
  |      PYTHON         |
  |  print("Hello!")    |
  |  Easy to read!      |
  +---------------------+
  

Mini summary: Python is a programming language. It is easy to read and write. It is great for beginners.

Lesson 2: Writing Your First Class

Definition: A class is a blueprint for creating objects. In Python, you write class Name:.

Why it is important: The class defines what data and actions the objects will have.

Simple explanation: You write the word class, then the name of the class, then a colon. Everything inside the class is indented.

Real-life example: A class called Car defines what a car looks like.

School example: A class called Student defines what a student looks like.

Home example: A class called Pet defines what a pet looks like.

Nigerian example: A class called Trader defines what a trader looks like.

Example code:

  class Car:
      pass
  

Illustration:

  class Car:
      pass
     |
     V
  A blueprint for cars
  

Mini summary: A class is written with the word class. It is a blueprint for objects.

Lesson 3: The __init__ Method – Setting Up Your Object

Definition: The __init__ method is a special method that runs when you create an object. It sets up the object’s data.

Why it is important: Every object needs to start with some data. __init__ gives it that data.

Simple explanation: When you create a car, you want to give it a colour and a speed. __init__ does that.

Real-life example: When a baby is born, it gets a name. __init__ is like giving the object its name.

School example: When a student joins a school, they get a name and a class. __init__ does that.

Home example: When you get a new phone, you set its name and wallpaper. __init__ does that.

Nigerian example: When you open a bank account, you get an account number. __init__ does that.

Example code:

  class Car:
      def __init__(self, colour, speed):
          self.colour = colour
          self.speed = speed
  

Illustration:

  __init__ runs
       |
       V
  Object gets data
       |
       V
  colour = "red"
  speed = 60
  

Mini summary: __init__ is a special method that sets up an object’s data when it is created.

Lesson 4: What is self?

Definition: self is a word that means “this object”. It is used inside a class to refer to the object being created or used.

Why it is important: Without self, Python does not know which object you are talking about.

Simple explanation: Imagine you have two cars. If you say “colour”, which car do you mean? self tells Python: “this car”.

Real-life example: When you say “my bag”, you mean your own bag. self means “my own”.

School example: When you say “my desk”, you mean your own desk. self means “my own”.

Home example: When you say “my room”, you mean your own room. self means “my own”.

Nigerian example: When you say “my shop”, you mean your own shop. self means “my own”.

Example code:

  class Car:
      def __init__(self, colour):
          self.colour = colour
  

Illustration:

  Object: Car 1
       |
       V
  self.colour = "red"
       |
       V
  This car's colour is red
  

Mini summary: self means “this object”. It is used inside a class to refer to the object.

Lesson 5: Creating an Object

Definition: Creating an object means making a specific thing from a class.

Why it is important: Objects are what you use in your program.

Simple explanation: You write the class name, then parentheses with the data. For example: my_car = Car("red", 60).

Real-life example: From the class Car, you create my_car.

School example: From the class Student, you create ada.

Home example: From the class Pet, you create bingo.

Nigerian example: From the class Trader, you create mama_nkechi.

Example code:

  my_car = Car("red", 60)
  

Illustration:

  Class: Car
       |
       V
  my_car = Car("red", 60)
       |
       V
  Object created!
  

Mini summary: Creating an object means making a specific thing from a class. You give it data.

Lesson 6: Giving Each Object Its Own Data

Definition: Each object can have its own data. This is called instance data.

Why it is important: It makes objects unique. Your car can be red. Your friend’s car can be blue.

Simple explanation: When you create an object, you pass in the data. Each object stores its own copy.

Real-life example: Two phones can have different colours.

School example: Two students can have different names.

Home example: Two pets can have different breeds.

Nigerian example: Two traders can sell different goods.

Example code:

  car1 = Car("red", 60)
  car2 = Car("blue", 80)
  print(car1.colour)  # red
  print(car2.colour)  # blue
  

Illustration:

  car1: colour = "red"
  car2: colour = "blue"
  Each object has its own data!
  

Mini summary: Each object can have its own data. This makes objects unique.

Lesson 7: Writing Methods

Definition: A method is a function inside a class. It defines what an object can do.

Why it is important: Methods let objects do things. They make objects useful.

Simple explanation: You write def method_name(self): inside the class. Then you write what the method does.

Real-life example: A car can drive. drive() is a method.

School example: A student can study. study() is a method.

Home example: A dog can bark. bark() is a method.

Nigerian example: A trader can sell. sell() is a method.

Example code:

  class Car:
      def __init__(self, colour, speed):
          self.colour = colour
          self.speed = speed

      def drive(self):
          print("The car is driving at " + str(self.speed) + " km/h")
  

Illustration:

  class Car:
      def drive(self):
          print("Driving!")
       |
       V
  Car can drive
  

Mini summary: A method is a function inside a class. It defines what an object can do.

Lesson 8: Calling Methods on an Object

Definition: Calling a method means telling the object to do the action.

Why it is important: Methods only work when you call them.

Simple explanation: You write the object name, then a dot, then the method name, then parentheses.

Real-life example: You press a button on your phone to make a call. That is calling a method.

School example: You raise your hand to answer a question. That is calling a method.

Home example: You press the remote to change the TV channel. That is calling a method.

Nigerian example: You tell the trader “I want to buy”. That is calling a method.

Example code:

  my_car = Car("red", 60)
  my_car.drive()
  

Output:

  The car is driving at 60 km/h
  

Illustration:

  my_car.drive()
       |
       V
  Method runs
       |
       V
  "The car is driving at 60 km/h"
  

Mini summary: Calling a method means telling the object to do the action. Use a dot and parentheses.

Lesson 9: Creating Multiple Objects

Definition: You can create many objects from one class.

Why it is important: This is the power of OOP. One class, many objects.

Simple explanation: You just call the class again with different data.

Real-life example: A factory makes many cars from one design.

School example: A school has many students from one admission form.

Home example: A bakery makes many cakes from one recipe.

Nigerian example: A tailor makes many dresses from one pattern.

Example code:

  car1 = Car("red", 60)
  car2 = Car("blue", 80)
  car3 = Car("green", 100)

  car1.drive()  # The car is driving at 60 km/h
  car2.drive()  # The car is driving at 80 km/h
  car3.drive()  # The car is driving at 100 km/h
  

Illustration:

  Class: Car
       |
       V
  +--------+ +--------+ +--------+
  | car1   | | car2   | | car3   |
  | red    | | blue   | | green  |
  | 60     | | 80     | | 100    |
  +--------+ +--------+ +--------+
  

Mini summary: You can create many objects from one class. Each object can have different data.

Lesson 10: Putting It All Together – A Complete Class

Definition: You will now write a complete class with __init__ and methods.

Why it is important: A complete class is the foundation of any OOP program.

Simple explanation: Start with class. Add __init__. Add methods. Create objects. Call methods.

Real-life example: A class called BankAccount with deposit and withdraw methods.

School example: A class called Student with study and play methods.

Home example: A class called Pet with eat and sleep methods.

Nigerian example: A class called Trader with buy and sell methods.

Example code:

  class Student:
      def __init__(self, name, age, grade):
          self.name = name
          self.age = age
          self.grade = grade

      def study(self):
          print(self.name + " is studying.")

      def play(self):
          print(self.name + " is playing.")

  ada = Student("Ada", 14, "JSS3")
  ada.study()
  ada.play()
  

Output:

  Ada is studying.
  Ada is playing.
  

Illustration:

  class Student:
      __init__ -> name, age, grade
      study() -> prints "studying"
      play() -> prints "playing"
       |
       V
  ada = Student("Ada", 14, "JSS3")
       |
       V
  ada.study() -> "Ada is studying."
  

Mini summary: A complete class has __init__ and methods. You create objects and call methods.

Lesson 11: Understanding the Dot Notation

Definition: Dot notation is using a dot to access an object’s data or methods.

Why it is important: You need dot notation to use objects.

Simple explanation: You write the object name, then a dot, then the attribute or method.

Real-life example: Like saying “my phone’s colour”.

School example: Like saying “Ada’s bag”.

Home example: Like saying “Bingo’s food”.

Nigerian example: Like saying “Mama Nkechi’s shop”.

Example code:

  my_car = Car("red", 60)
  print(my_car.colour)  # red
  my_car.drive()        # The car is driving at 60 km/h
  

Illustration:

  my_car.colour
     |     |
     |     V
     |  attribute
     V
  object
  

Mini summary: Dot notation lets you access an object’s data and methods. Use a dot.

Lesson 12: Adding More Methods

Definition: You can add as many methods as you want to a class.

Why it is important: More methods make your objects more useful.

Simple explanation: Just write another def inside the class.

Real-life example: A phone can call, text, and take photos.

School example: A student can study, play, and write.

Home example: A dog can bark, run, and eat.

Nigerian example: A trader can buy, sell, and count money.

Example code:

  class Car:
      def __init__(self, colour, speed):
          self.colour = colour
          self.speed = speed

      def drive(self):
          print("Driving at " + str(self.speed) + " km/h")

      def stop(self):
          print("Car has stopped.")

      def honk(self):
          print("Beep beep!")
  

Illustration:

  class Car:
      drive()
      stop()
      honk()
  

Mini summary: You can add many methods to a class. Each method defines an action.

Lesson 13: Using Objects in a Program

Definition: Using objects means creating them and calling their methods in your program.

Why it is important: This is how OOP programs work.

Simple explanation: You create objects, then call methods on them.

Real-life example: A game creates characters and makes them move.

School example: A school program creates students and makes them study.

Home example: A smart home program creates lights and turns them on.

Nigerian example: A market program creates traders and makes them sell.

Example code:

  car1 = Car("red", 60)
  car2 = Car("blue", 80)

  car1.drive()
  car2.drive()
  car1.stop()
  car2.honk()
  

Output:

  Driving at 60 km/h
  Driving at 80 km/h
  Car has stopped.
  Beep beep!
  

Illustration:

  Create car1 -> drive() -> stop()
  Create car2 -> drive() -> honk()
  

Mini summary: Using objects means creating them and calling their methods. This is how OOP programs work.

Lesson 14: Common Mistakes When Writing Classes

Definition: These are mistakes beginners often make.

Why it is important: Knowing them helps you avoid them.

Simple explanation: Here are some mistakes to watch out for.

List of mistakes:

  • Forgetting to put self in the method.
  • Forgetting to indent the code inside the class.
  • Forgetting to call __init__ with the right number of arguments.
  • Using the wrong variable name.
  • Forgetting to create an object before calling a method.

Illustration:

  Bad Code                Good Code
  +----------------+      +----------------+
  | def drive():   |      | def drive(self):|
  |     print()    |      |     print()    |
  +----------------+      +----------------+
  

Mini summary: Avoid common mistakes. Always use self. Always indent. Always create objects first.

Lesson 15: Your First Complete Program – Review and Celebrate

Definition: You have written a complete class and created objects.

Why it is important: Reviewing helps you remember.

Simple explanation: You learned how to write a class, use __init__, use self, create objects, and call methods.

Real-life example: Like finishing a small project.

School example: Like finishing your first essay.

Home example: Like cooking your first meal.

Nigerian example: Like making your first pot of jollof rice.

Illustration:

  Write class
       |
       V
  Add __init__
       |
       V
  Add methods
       |
       V
  Create objects
       |
       V
  Call methods
       |
       V
  Celebrate 🎉
  

Mini summary: You wrote your first complete program. You are now an OOP programmer!

📖 Key Vocabulary

WordSimple Definition
PythonA programming language that is easy to read.
ClassA blueprint for creating objects.
ObjectA thing made from a class.
InstanceAnother word for an object.
__init__A special method that sets up an object’s data.
selfA word that means “this object”.
AttributeData that an object holds.
MethodAn action that an object can do.
Dot notationUsing a dot to access data or methods.
ArgumentA value you pass to a method.
IndentMoving code to the right.
CallTo run a method.

🔑 Important Concepts

  • Python is easy: It reads like English.
  • Class is a blueprint: You write class Name:.
  • __init__ sets up data: It runs when you create an object.
  • self means “this object”: It is used inside the class.
  • Object is a thing: You create it with Name(data).
  • Methods are actions: You write def method(self):.
  • Dot notation accesses data: Use a dot.
  • One class, many objects: Create as many as you want.

🧭 Step-by-Step Explanations

How to write a class

  1. Write class Name:.
  2. Indent the next lines.
  3. Write def __init__(self, ...):.
  4. Set up attributes with self.attribute = value.
  5. Write other methods with def method(self):.

How to create an object

  1. Write the class name.
  2. Add parentheses with the data.
  3. Example: my_car = Car("red", 60).

How to call a method

  1. Write the object name.
  2. Add a dot.
  3. Write the method name and parentheses.
  4. Example: my_car.drive().

🌍 Real-life Examples

  • A car class with colour and speed.
  • A student class with name and age.
  • A bank account class with balance and deposit.
  • A pet class with name and breed.
  • A phone class with brand and call.

🇳🇬 Nigerian Examples

  • A trader class with name and goods.
  • A danfo bus class with route and fare.
  • A student class with name and class.
  • A bank account class with balance.
  • A market stall class with owner and goods.

🎈 Fun Examples Children Can Relate To

  • A video game character class with health and attack.
  • A football class with size and bounce.
  • A toy class with colour and sound.
  • A pet class with name and run.
  • A bicycle class with wheels and move.

🏠 Everyday Examples

  • Your phone is an object with data and actions.
  • Your school bag is an object with data and actions.
  • Your fridge is an object with data and actions.
  • Your television is an object with data and actions.
  • Your watch is an object with data and actions.

👨‍👩‍👧 Parent Tips

  • Encourage your child to write simple classes.
  • Ask them to explain what a class and an object are.
  • Help them install Python on a computer.
  • Celebrate when they create their first object.
  • Remind them that mistakes are part of learning.

💡 Interesting Facts

  • Python was created in 1991.
  • It is named after a comedy group called Monty Python.
  • Python is used by Google, NASA, and Netflix.
  • You can write Python on any computer.
  • Python is one of the most popular languages in the world.

🤔 Did You Know?

  • Did you know that a class can have no objects?
  • Did you know that one class can make thousands of objects?
  • Did you know that objects can have other objects inside them?
  • Did you know that self is not a special word in Python?
  • Did you know that you can change an object’s data after creating it?

📌 Remember This

  • Python is easy to read.
  • Class is a blueprint.
  • Object is a thing made from a class.
  • __init__ sets up data.
  • self means “this object”.
  • Methods are actions.
  • Dot notation accesses data and methods.
  • One class can make many objects.

⚠️ Common Mistakes

  • Forgetting self in methods.
  • Forgetting to indent.
  • Wrong number of arguments.
  • Wrong variable name.
  • Forgetting to create an object before calling a method.

✅ Best Practices

  • Always use self.
  • Always indent properly.
  • Give classes clear names.
  • Give methods clear names.
  • Test your code often.
  • Keep your code organised.

📊 Illustrations, Diagrams, and Tables

Flowchart: Writing a Class and Creating Objects

  Write class
        |
        V
  Add __init__
        |
        V
  Add methods
        |
        V
  Create object
        |
        V
  Call methods
        |
        V
  See output! 🎉
  

Timeline: Your Python Journey

  Lesson 1: What is Python?
  Lesson 2: Write a class
  Lesson 3: __init__
  Lesson 4: self
  Lesson 5: Create object
  Lesson 6: Own data
  Lesson 7: Methods
  Lesson 8: Call methods
  Lesson 9: Multiple objects
  Lesson 10: Complete class
  Lesson 11: Dot notation
  Lesson 12: More methods
  Lesson 13: Use objects
  Lesson 14: Avoid mistakes
  Lesson 15: Complete program
  

Table: Class vs Object

FeatureClassObject
What is it?A blueprintA thing made from the blueprint
How many?One classMany objects
ExampleCar designYour red car
Exists in memory?NoYes

Table: Attributes vs Methods

FeatureAttributesMethods
What are they?DataActions
Example (Student)name, agestudy, play
Example (Car)colour, speeddrive, stop

📝 Summary After Every Lesson

Lesson 1: Python is a programming language. It is easy to read and write.

Lesson 2: A class is written with the word class.

Lesson 3: __init__ is a special method that sets up an object’s data.

Lesson 4: self means “this object”.

Lesson 5: Creating an object means making a specific thing from a class.

Lesson 6: Each object can have its own data.

Lesson 7: A method is a function inside a class.

Lesson 8: Calling a method means telling the object to do the action.

Lesson 9: You can create many objects from one class.

Lesson 10: A complete class has __init__ and methods.

Lesson 11: Dot notation lets you access an object’s data and methods.

Lesson 12: You can add many methods to a class.

Lesson 13: Using objects means creating them and calling their methods.

Lesson 14: Avoid common mistakes. Always use self. Always indent.

Lesson 15: You wrote your first complete program. You are an OOP programmer!

📦 End-of-Module Summary

In this module, you learned how to create classes and objects in Python. You learned what Python is and why it is good for beginners. You wrote your first class. You learned about __init__ and self. You created objects and gave them their own data. You wrote methods and called them. You created multiple objects from one class. You learned about dot notation. You also learned to avoid common mistakes. You wrote your first complete OOP program. You are now ready for Module Three, where you will learn about inheritance and polymorphism.

❓ Frequently Asked Questions (10 questions)

  1. What is Python? A programming language that is easy to read.
  2. How do I write a class? Write class Name: and indent the code.
  3. What is __init__? A special method that sets up an object’s data.
  4. What is self? A word that means “this object”.
  5. How do I create an object? Write the class name with parentheses and data.
  6. What is a method? A function inside a class.
  7. How do I call a method? Write the object name, a dot, and the method name.
  8. Can I create many objects? Yes, as many as you want.
  9. What is dot notation? Using a dot to access data or methods.
  10. What are common mistakes? Forgetting self, forgetting to indent, wrong arguments.

🔗 Matching Exercises

Match the word to its meaning.

WordMeaning
1. ClassA. A special method that sets up data
2. ObjectB. A blueprint for creating objects
3. __init__C. A thing made from a class
4. selfD. An action that an object can do
5. MethodE. A word that means “this object”

Answers: 1-B, 2-C, 3-A, 4-E, 5-D

🧩 Scenario-based Exercises

  1. You want to create a class for cars. What do you write first? (class Car:)
  2. You want to give each car a colour. Where do you set it? (In __init__)
  3. You create a car called my_car. How do you make it drive? (my_car.drive())
  4. You want to access the car’s colour. How do you do it? (my_car.colour)
  5. You want to create three cars. How many classes do you need? (One)

👥 Group Activity

Title: Write a Class Together

Instructions: In groups of 3, choose a thing (e.g., a phone, a student, a pet). Write a class in Python. Add __init__ and at least two methods. Create two objects from the class. Run the code together. Present to the class.

🧑 Individual Activity

Title: My First Class

Instructions: Write a class called MyPet. Add __init__ with name and type. Add two methods: eat() and sleep(). Create two objects. Call the methods. Write down what happens.

🛠️ Mini Project

Title: A Class for Your School

Instructions: Write a class called Student. Add __init__ with name, age, and grade. Add methods: study(), play(), and write(). Create three students. Call the methods. Print the results.

📋 Practical Assignment

Task: Write a short paragraph (5 sentences) explaining what you learned about classes and objects. Then, list three things you found easy and one thing you found hard. Finally, describe the class you created and what it does.

🔑 Key Takeaways

  • Python is easy to read and write.
  • A class is a blueprint for objects.
  • An object is a thing made from a class.
  • __init__ sets up an object’s data.
  • self means “this object”.
  • Methods are actions that objects can do.
  • Dot notation accesses data and methods.
  • One class can make many objects.
  • Always test your code.

💬 Classroom Discussion Questions

  1. Why is Python good for beginners?
  2. What is the difference between a class and an object?
  3. What does self mean?
  4. How do you create an object?
  5. What would you like to build with classes and objects?

➡️ Preparation for the Next Module

In Module Three, we will learn about inheritance and polymorphism. You will learn how one class can inherit from another. You will learn how to reuse code. To get ready, make sure you:

  • Understand how to write a class.
  • Know how to create objects.
  • Know how to call methods.
  • Have practised writing your own classes.

See you in Module Three! 🚀


End of Module Two · Object Oriented Programming

4

Module Three

Module Three · Object Oriented Programming

📘 Module Three: Inheritance and Polymorphism – Building on What You Know

🌟 Module Introduction

Welcome back, programmer! In Module One, you learned what Object Oriented Programming is. You learned about objects and classes. In Module Two, you learned how to write classes and create objects in Python. You learned about __init__, self, attributes, and methods.

Now imagine you want to create a program about animals. You have dogs, cats, and birds. They all have names and ages. They all eat and sleep. But dogs can bark. Cats can meow. Birds can fly. Do you want to write the same code for name, age, eat, and sleep three times? That would be a lot of work.

This is where inheritance comes in. Inheritance lets one class get all the data and methods from another class. Then you can add new things or change things. It saves time and keeps your code organised.

We will also learn about polymorphism. Polymorphism means “many forms”. It lets different objects respond to the same action in their own way. A dog barks. A cat meows. Both respond to “make a sound”, but in different ways.

By the end of this module, you will be able to create parent classes and child classes. You will understand how to reuse code. You will see how polymorphism makes programs flexible. Let’s begin!

🎯 Learning Objectives

After you finish this module, you will be able to:

  • Explain what inheritance is.
  • Explain why inheritance is useful.
  • Create a parent class.
  • Create a child class that inherits from a parent.
  • Add new attributes and methods to a child class.
  • Override methods in a child class.
  • Use the super() function to call the parent’s methods.
  • Explain what polymorphism is.
  • See polymorphism in action with different objects.
  • Understand the “is-a” relationship.
  • Avoid common mistakes with inheritance.
  • Feel confident to use inheritance in your own programs.

📖 Warm-up Story: Tunde and the Family of Cars

Tunde lived in Ibadan. His father owned a car workshop. One day, Tunde asked his father, “Papa, how do you build different types of cars? You have taxis, buses, and private cars. They are all different, but they all have wheels and engines.”

His father smiled. “That is a good question,” he said. “We start with a basic design. Every car has wheels, an engine, and a steering wheel. That is the parent design. Then, for a taxi, we add a taxi sign and a meter. For a bus, we add many seats. For a private car, we add comfortable seats.”

Tunde understood. “So the basic design is like a parent class,” he said. “And the taxi, bus, and private car are like child classes. They inherit from the parent, but they add their own special things.”

His father nodded. “Exactly! And here is the amazing part. If we need to change the engine design, we only change it in the parent design. All the child designs get the update automatically. That saves us a lot of work.”

Tunde was excited. He decided to learn more about inheritance. He wanted to write code that reused ideas, just like his father’s workshop.

Moral of the story: Inheritance lets you build on what you already have. You write common things once in a parent class, and child classes get them for free.

📚 Main Lessons

Lesson 1: What is Inheritance?

Definition: Inheritance is when one class gets the attributes and methods of another class.

Why it is important: It saves time. You write common code once, and reuse it many times.

Simple explanation: Imagine you have a recipe for bread. You can use that recipe to make different types of bread: white bread, brown bread, and banana bread. You do not need to write the basic bread recipe again. You just add the special ingredients.

Real-life example: A smartphone inherits from a basic phone. It can call and text (from the basic phone), but it can also take photos and browse the internet.

School example: A science student inherits from a student. They have a name and age (from student), but they also study science subjects.

Home example: A puppy inherits from a dog. It has fur and a tail (from dog), but it is smaller and drinks milk.

Nigerian example: A danfo bus inherits from a vehicle. It has wheels and an engine (from vehicle), but it also has yellow paint and a conductor.

Illustration:

  Parent Class: Vehicle
       |
       V
  +--------+ +--------+ +--------+
  | Car    | | Bus    | | Danfo  |
  +--------+ +--------+ +--------+
  Child Classes inherit from Vehicle
  

Mini summary: Inheritance lets one class get the data and actions of another class. It saves time and keeps code organised.

Lesson 2: Parent Class and Child Class

Definition: A parent class is the class being inherited from. A child class is the class that inherits.

Why it is important: You need to know the difference to use inheritance correctly.

Simple explanation: The parent class is like a mother. The child class is like her child. The child gets some things from the mother, but also has its own things.

Real-life example: A vehicle is a parent class. A car is a child class.

School example: A person is a parent class. A student is a child class.

Home example: An animal is a parent class. A dog is a child class.

Nigerian example: A trader is a parent class. A food trader is a child class.

Illustration:

  Parent Class: Animal
       |
       V
  Child Class: Dog
       |
       V
  Dog inherits from Animal
  

Mini summary: A parent class is inherited from. A child class inherits. The child gets things from the parent.

Lesson 3: The “Is-A” Relationship

Definition: Inheritance creates an “is-a” relationship. A child class “is a” type of parent class.

Why it is important: It helps you know when to use inheritance.

Simple explanation: A dog “is an” animal. A car “is a” vehicle. A student “is a” person.

Real-life example: A smartphone “is a” phone.

School example: A science student “is a” student.

Home example: A puppy “is a” dog.

Nigerian example: A danfo “is a” vehicle.

Illustration:

  Dog IS-A Animal  ✓
  Car IS-A Vehicle ✓
  Student IS-A Person ✓

  Dog IS-A Car     ✗ (not correct)
  

Mini summary: Inheritance creates an “is-a” relationship. If the child “is a” type of parent, inheritance makes sense.

Lesson 4: Creating a Parent Class

Definition: A parent class is a normal class that other classes will inherit from.

Why it is important: It holds the common code that all child classes will share.

Simple explanation: You write a class with common attributes and methods. Then child classes can use them.

Real-life example: A parent class called Animal with name and age.

School example: A parent class called Person with name and age.

Home example: A parent class called Appliance with brand and power.

Nigerian example: A parent class called Vehicle with wheels and engine.

Example code:

  class Animal:
      def __init__(self, name, age):
          self.name = name
          self.age = age

      def eat(self):
          print(self.name + " is eating.")

      def sleep(self):
          print(self.name + " is sleeping.")
  

Illustration:

  class Animal:
      __init__ -> name, age
      eat() -> "eating"
      sleep() -> "sleeping"
  

Mini summary: A parent class holds common attributes and methods. Child classes will inherit them.

Lesson 5: Creating a Child Class

Definition: A child class inherits from a parent class. You write the parent class name in parentheses.

Why it is important: Child classes get all the parent’s attributes and methods for free.

Simple explanation: You write class Dog(Animal):. The (Animal) means Dog inherits from Animal.

Real-life example: A child class called Dog inherits from Animal.

School example: A child class called ScienceStudent inherits from Student.

Home example: A child class called SmartPhone inherits from Phone.

Nigerian example: A child class called Danfo inherits from Vehicle.

Example code:

  class Dog(Animal):
      def bark(self):
          print(self.name + " is barking.")
  

Illustration:

  class Animal:
      name, age
      eat(), sleep()
       |
       V
  class Dog(Animal):
      bark()
  Dog inherits eat and sleep from Animal
  

Mini summary: A child class inherits from a parent by writing the parent’s name in parentheses.

Lesson 6: Adding New Methods to a Child Class

Definition: You can add new methods to a child class that the parent does not have.

Why it is important: It lets the child class do things that are special to it.

Simple explanation: A dog can bark. An animal cannot bark. So bark() is added only to the Dog class.

Real-life example: A smartphone can take photos. A basic phone cannot.

School example: A science student can do experiments. A normal student cannot.

Home example: A smart TV can browse the internet. A normal TV cannot.

Nigerian example: A danfo can carry many passengers. A private car cannot.

Example code:

  class Dog(Animal):
      def bark(self):
          print(self.name + " is barking.")

  my_dog = Dog("Bingo", 3)
  my_dog.eat()   # inherited from Animal
  my_dog.bark()  # added in Dog
  

Output:

  Bingo is eating.
  Bingo is barking.
  

Illustration:

  Animal: eat(), sleep()
  Dog: eat(), sleep() + bark()
  

Mini summary: Child classes can add new methods. These are special actions that only the child can do.

Lesson 7: Overriding Methods

Definition: Overriding means changing a method in the child class that already exists in the parent class.

Why it is important: Sometimes the child needs to do something differently.

Simple explanation: The parent says “eat”. The child says “eat differently”.

Real-life example: A baby eats milk. An adult eats rice. Both “eat”, but differently.

School example: A JSS1 student studies basic maths. A JSS3 student studies harder maths. Both “study”, but differently.

Home example: A puppy sleeps a lot. An adult dog sleeps less. Both “sleep”, but differently.

Nigerian example: A small trader sells from a tray. A big trader sells from a shop. Both “sell”, but differently.

Example code:

  class Animal:
      def __init__(self, name):
          self.name = name

      def speak(self):
          print(self.name + " makes a sound.")

  class Dog(Animal):
      def speak(self):
          print(self.name + " barks.")

  class Cat(Animal):
      def speak(self):
          print(self.name + " meows.")

  my_dog = Dog("Bingo")
  my_cat = Cat("Fluffy")

  my_dog.speak()  # Bingo barks.
  my_cat.speak()  # Fluffy meows.
  

Illustration:

  Animal.speak() -> "makes a sound"
  Dog.speak()    -> "barks"
  Cat.speak()    -> "meows"
  

Mini summary: Overriding means changing a method in the child class. The child does it differently.

Lesson 8: Using super() to Call the Parent

Definition: super() is a function that lets you call a method from the parent class.

Why it is important: Sometimes you want to use the parent’s method and then add more.

Simple explanation: You say “do what the parent does, then do this extra thing”.

Real-life example: A child says “Thank you” like their parent, then adds “sir” or “madam”.

School example: A student follows the school rules, then adds their own study rules.

Home example: You follow your family recipe, then add your own spice.

Nigerian example: You follow your mother’s jollof recipe, then add your own special pepper.

Example code:

  class Animal:
      def __init__(self, name, age):
          self.name = name
          self.age = age

      def introduce(self):
          print("I am " + self.name + " and I am " + str(self.age) + " years old.")

  class Dog(Animal):
      def __init__(self, name, age, breed):
          super().__init__(name, age)
          self.breed = breed

      def introduce(self):
          super().introduce()
          print("I am a " + self.breed + ".")

  my_dog = Dog("Bingo", 3, "Labrador")
  my_dog.introduce()
  

Output:

  I am Bingo and I am 3 years old.
  I am a Labrador.
  

Illustration:

  Dog.__init__
       |
       V
  super().__init__(name, age) -> sets name and age
       |
       V
  self.breed = breed -> sets breed
  

Mini summary: super() lets you call the parent’s method. You can use it and then add more.

Lesson 9: What is Polymorphism?

Definition: Polymorphism means “many forms”. It lets different objects respond to the same action in their own way.

Why it is important: It makes programs flexible. You can write one piece of code that works with many types of objects.

Simple explanation: If you say “speak” to a dog, it barks. If you say “speak” to a cat, it meows. Same action, different results.

Real-life example: If you press “play” on a phone, it plays music. If you press “play” on a video player, it plays video.

School example: If you say “write” to a student, they write with a pen. If you say “write” to a computer, it writes on the screen.

Home example: If you say “cook” to a microwave, it heats food. If you say “cook” to a cooker, it boils food.

Nigerian example: If you say “sell” to a food trader, they sell food. If you say “sell” to a cloth trader, they sell cloth.

Illustration:

  Action: speak()
       |
       V
  +--------+ +--------+ +--------+
  | Dog    | | Cat    | | Cow    |
  | barks  | | meows  | | moos   |
  +--------+ +--------+ +--------+
  Same action, different results!
  

Mini summary: Polymorphism means “many forms”. Different objects can respond to the same action in their own way.

Lesson 10: Polymorphism in Action

Definition: You can use polymorphism by calling the same method on different objects.

Why it is important: It lets you write flexible code.

Simple explanation: You write a loop that goes through a list of animals. You call speak() on each one. Each animal speaks in its own way.

Real-life example: A remote control has a “power” button. It works on the TV, the fan, and the air conditioner.

School example: A teacher says “introduce yourself”. Each student says their own name.

Home example: You say “clean” to your broom, your mop, and your vacuum. Each cleans differently.

Nigerian example: You say “cook” to your pot, your pan, and your oven. Each cooks differently.

Example code:

  animals = [Dog("Bingo"), Cat("Fluffy"), Cow("Buttercup")]

  for animal in animals:
      animal.speak()
  

Output:

  Bingo barks.
  Fluffy meows.
  Buttercup moos.
  

Illustration:

  for animal in animals:
      animal.speak()
       |
       V
  Dog.speak() -> barks
  Cat.speak() -> meows
  Cow.speak() -> moos
  

Mini summary: Polymorphism lets you call the same method on different objects. Each object responds in its own way.

Lesson 11: Inheritance and Polymorphism Together

Definition: You can use inheritance and polymorphism together.

Why it is important: This is the power of OOP.

Simple explanation: You create a parent class with a method. Child classes override the method. Then you can use polymorphism to call the method on any child.

Real-life example: A vehicle parent class has a move() method. Cars, buses, and bikes override it.

School example: A person parent class has a study() method. Science, art, and commercial students override it.

Home example: An appliance parent class has a work() method. Fridge, fan, and cooker override it.

Nigerian example: A trader parent class has a sell() method. Food, cloth, and phone traders override it.

Example code:

  class Vehicle:
      def __init__(self, name):
          self.name = name

      def move(self):
          print(self.name + " is moving.")

  class Car(Vehicle):
      def move(self):
          print(self.name + " is driving on the road.")

  class Boat(Vehicle):
      def move(self):
          print(self.name + " is sailing on the water.")

  class Plane(Vehicle):
      def move(self):
          print(self.name + " is flying in the sky.")

  vehicles = [Car("Toyota"), Boat("Canoe"), Plane("Boeing")]

  for v in vehicles:
      v.move()
  

Output:

  Toyota is driving on the road.
  Canoe is sailing on the water.
  Boeing is flying in the sky.
  

Illustration:

  Vehicle.move()
       |
       V
  Car.move()   -> driving
  Boat.move()  -> sailing
  Plane.move() -> flying
  

Mini summary: Inheritance and polymorphism work together. The parent defines the method. The children override it. Polymorphism calls it on any child.

Lesson 12: When to Use Inheritance

Definition: Inheritance is best when there is an “is-a” relationship and shared code.

Why it is important: Using inheritance wrongly makes code confusing.

Simple explanation: Use inheritance when the child “is a” type of parent and they share common things.

Real-life example: A car “is a” vehicle. Use inheritance. A car “has an” engine. Do not use inheritance; use an attribute.

School example: A student “is a” person. Use inheritance. A student “has a” bag. Do not use inheritance.

Home example: A dog “is an” animal. Use inheritance. A dog “has a” collar. Do not use inheritance.

Nigerian example: A danfo “is a” vehicle. Use inheritance. A danfo “has a” conductor. Do not use inheritance.

Illustration:

  IS-A relationship  -> Use inheritance
  HAS-A relationship -> Use attribute

  Dog IS-A Animal    -> inheritance
  Dog HAS-A Collar   -> attribute
  

Mini summary: Use inheritance for “is-a” relationships. Use attributes for “has-a” relationships.

Lesson 13: Types of Inheritance

Definition: There are different ways classes can inherit from each other.

Why it is important: Knowing the types helps you design your classes.

Simple explanation: You can have single inheritance (one parent), multilevel inheritance (parent, child, grandchild), and multiple inheritance (many parents).

Real-life example: A grandfather, a father, and a son are multilevel inheritance.

School example: A person, a student, and a science student are multilevel inheritance.

Home example: An appliance, a kitchen appliance, and a fridge are multilevel inheritance.

Nigerian example: A vehicle, a bus, and a luxury bus are multilevel inheritance.

Table: Types of Inheritance

TypeDescriptionExample
SingleOne parent, one childAnimal → Dog
MultilevelParent → Child → GrandchildAnimal → Dog → Puppy
MultipleMany parents, one childFlyer + Swimmer → Duck

Illustration:

  Single:     Animal
                |
              Dog

  Multilevel: Animal
                |
              Dog
                |
              Puppy
  

Mini summary: There are different types of inheritance: single, multilevel, and multiple. Start with single inheritance.

Lesson 14: Common Mistakes with Inheritance

Definition: These are mistakes beginners often make.

Why it is important: Knowing them helps you avoid them.

Simple explanation: Here are some mistakes to watch out for.

List of mistakes:

  • Using inheritance when there is no “is-a” relationship.
  • Forgetting to call super().__init__().
  • Overriding a method and forgetting to use super() when needed.
  • Making the parent class too specific.
  • Creating too many levels of inheritance.

Illustration:

  Bad Inheritance          Good Inheritance
  +----------------+       +----------------+
  | Car IS-A Engine|       | Car IS-A Vehicle|
  | (wrong)        |       | (correct)      |
  +----------------+       +----------------+
  

Mini summary: Avoid common mistakes. Use inheritance only for “is-a”. Always call super().__init__().

Lesson 15: Putting It All Together – A Complete Program

Definition: You will now combine inheritance and polymorphism in one program.

Why it is important: This is how real OOP programs work.

Simple explanation: Create a parent class. Create child classes. Override methods. Use a loop to call the same method on all objects.

Real-life example: A zoo program with different animals.

School example: A school program with different types of students.

Home example: A smart home program with different appliances.

Nigerian example: A market program with different types of traders.

Example code:

  class Animal:
      def __init__(self, name):
          self.name = name

      def speak(self):
          print(self.name + " makes a sound.")

      def eat(self):
          print(self.name + " is eating.")

  class Dog(Animal):
      def speak(self):
          print(self.name + " barks.")

  class Cat(Animal):
      def speak(self):
          print(self.name + " meows.")

  class Cow(Animal):
      def speak(self):
          print(self.name + " moos.")

  animals = [Dog("Bingo"), Cat("Fluffy"), Cow("Buttercup")]

  for animal in animals:
      animal.eat()
      animal.speak()
      print("---")
  

Output:

  Bingo is eating.
  Bingo barks.
  ---
  Fluffy is eating.
  Fluffy meows.
  ---
  Buttercup is eating.
  Buttercup moos.
  ---
  

Illustration:

  Animal (parent)
      |
      V
  +--------+ +--------+ +--------+
  | Dog    | | Cat    | | Cow    |
  | speak  | | speak  | | speak  |
  | barks  | | meows  | | moos   |
  +--------+ +--------+ +--------+
  All inherit eat() from Animal
  

Mini summary: You can combine inheritance and polymorphism. One parent class, many child classes, and one loop to call them all.

📖 Key Vocabulary

WordSimple Definition
InheritanceWhen one class gets the data and actions of another class.
Parent classThe class being inherited from.
Child classThe class that inherits.
OverrideChanging a method in the child class.
super()A function that calls the parent’s method.
Polymorphism“Many forms” – different objects respond to the same action differently.
Is-a relationshipWhen a child “is a” type of parent.
Has-a relationshipWhen a class “has a” thing as an attribute.
Single inheritanceOne parent, one child.
Multilevel inheritanceParent → Child → Grandchild.
Multiple inheritanceMany parents, one child.
ReuseUsing code again.

🔑 Important Concepts

  • Inheritance saves time: Write common code once.
  • Parent and child: Child inherits from parent.
  • Is-a relationship: Use inheritance when child “is a” parent.
  • Override: Child can change a parent’s method.
  • super(): Call the parent’s method.
  • Polymorphism: Same action, different results.
  • Inheritance + polymorphism: Powerful together.
  • Use inheritance wisely: Only for “is-a” relationships.

🧭 Step-by-Step Explanations

How to create a parent class

  1. Write class ParentName:.
  2. Add __init__ with common attributes.
  3. Add common methods.

How to create a child class

  1. Write class ChildName(ParentName):.
  2. Add new attributes and methods.
  3. Override methods if needed.
  4. Use super() to call parent methods.

How to use polymorphism

  1. Create objects of different child classes.
  2. Put them in a list.
  3. Loop through the list.
  4. Call the same method on each object.

🌍 Real-life Examples

  • A vehicle parent class with car, bus, and bike children.
  • An animal parent class with dog, cat, and cow children.
  • A person parent class with student and teacher children.
  • An appliance parent class with fridge, fan, and cooker children.
  • A shape parent class with circle, square, and triangle children.

🇳🇬 Nigerian Examples

  • A trader parent class with food, cloth, and phone trader children.
  • A vehicle parent class with danfo, keke, and okada children.
  • A student parent class with science, art, and commercial children.
  • A market stall parent class with vegetable, meat, and fish children.
  • A bank account parent class with savings and current children.

🎈 Fun Examples Children Can Relate To

  • A video game character parent with hero, enemy, and boss children.
  • A toy parent class with car, doll, and ball children.
  • A pet parent class with dog, cat, and parrot children.
  • A food parent class with rice, beans, and yam children.
  • A sport parent class with football, basketball, and tennis children.

🏠 Everyday Examples

  • A phone parent class with basic phone and smartphone children.
  • A bag parent class with school bag, handbag, and shopping bag children.
  • A shoe parent class with sandal, sneaker, and boot children.
  • A drink parent class with water, juice, and tea children.
  • A furniture parent class with chair, table, and bed children.

👨‍👩‍👧 Parent Tips

  • Encourage your child to see inheritance in everyday life.
  • Ask them to explain the “is-a” relationship.
  • Help them create a simple parent and child class.
  • Celebrate when they make polymorphism work.
  • Remind them that inheritance saves time.

💡 Interesting Facts

  • Inheritance was invented in the 1960s.
  • It is one of the four pillars of OOP.
  • Python supports multiple inheritance.
  • Java does not support multiple inheritance with classes.
  • Polymorphism comes from Greek words meaning “many forms”.

🤔 Did You Know?

  • Did you know that a child class can have its own child class?
  • Did you know that super() can call any method, not just __init__?
  • Did you know that polymorphism works with functions too?
  • Did you know that you can check if an object is an instance of a class?
  • Did you know that inheritance can make code easier to fix?

📌 Remember This

  • Inheritance lets one class get data and methods from another.
  • Parent class is inherited from. Child class inherits.
  • Use inheritance for “is-a” relationships.
  • Override means changing a method in the child.
  • super() calls the parent’s method.
  • Polymorphism means “many forms”.
  • Same action, different results.
  • Inheritance and polymorphism work together.

⚠️ Common Mistakes

  • Using inheritance when there is no “is-a” relationship.
  • Forgetting to call super().__init__().
  • Overriding a method and forgetting to use super() when needed.
  • Making the parent class too specific.
  • Creating too many levels of inheritance.

✅ Best Practices

  • Use inheritance only for “is-a” relationships.
  • Always call super().__init__() in the child.
  • Keep the parent class general.
  • Use clear names for classes.
  • Test your code often.
  • Keep inheritance simple.

📊 Illustrations, Diagrams, and Tables

Flowchart: Inheritance and Polymorphism

  Create Parent Class
        |
        V
  Create Child Classes
        |
        V
  Override Methods
        |
        V
  Create Objects
        |
        V
  Loop and Call Same Method
        |
        V
  Polymorphism! 🎉
  

Timeline: Your OOP Journey

  Module 1: What is OOP?
  Module 2: Classes and Objects
  Module 3: Inheritance and Polymorphism
  Module 4: Encapsulation and Abstraction
  Module 5: Putting It All Together
  

Table: Parent vs Child Class

FeatureParent ClassChild Class
Also calledBase classDerived class
What it hasCommon attributes and methodsCommon + special attributes and methods
ExampleAnimalDog
Inherits fromNothingParent

Comparison Table: Inheritance vs Polymorphism

FeatureInheritancePolymorphism
What it doesReuses codeMany forms
RelationshipIs-aSame action, different results
ExampleDog inherits AnimalDog barks, Cat meows
Key wordclass Dog(Animal):Same method name

📝 Summary After Every Lesson

Lesson 1: Inheritance lets one class get the data and actions of another class.

Lesson 2: A parent class is inherited from. A child class inherits.

Lesson 3: Inheritance creates an “is-a” relationship.

Lesson 4: A parent class holds common attributes and methods.

Lesson 5: A child class inherits by writing the parent’s name in parentheses.

Lesson 6: Child classes can add new methods.

Lesson 7: Overriding means changing a method in the child class.

Lesson 8: super() calls the parent’s method.

Lesson 9: Polymorphism means “many forms”.

Lesson 10: Polymorphism lets you call the same method on different objects.

Lesson 11: Inheritance and polymorphism work together.

Lesson 12: Use inheritance for “is-a” relationships.

Lesson 13: There are different types of inheritance: single, multilevel, and multiple.

Lesson 14: Avoid common mistakes. Use inheritance wisely.

Lesson 15: You can combine inheritance and polymorphism in one program.

📦 End-of-Module Summary

In this module, you learned about inheritance and polymorphism. You learned that inheritance lets one class get the data and methods of another class. You learned about parent classes and child classes. You learned about the “is-a” relationship. You learned how to create a parent class and a child class. You learned how to add new methods and override existing ones. You learned how to use super() to call the parent’s method. You learned what polymorphism is and how it lets different objects respond to the same action in their own way. You also learned when to use inheritance and how to avoid common mistakes. You are now ready for Module Four, where you will learn about encapsulation and abstraction.

❓ Frequently Asked Questions (10 questions)

  1. What is inheritance? When one class gets the data and actions of another class.
  2. What is a parent class? The class being inherited from.
  3. What is a child class? The class that inherits.
  4. What is the “is-a” relationship? When a child “is a” type of parent.
  5. How do I create a child class? Write class Child(Parent):.
  6. What is overriding? Changing a method in the child class.
  7. What is super()? A function that calls the parent’s method.
  8. What is polymorphism? “Many forms” – different objects respond to the same action differently.
  9. When should I use inheritance? When there is an “is-a” relationship.
  10. What are common mistakes? Using inheritance wrongly, forgetting super().

🔗 Matching Exercises

Match the word to its meaning.

WordMeaning
1. InheritanceA. Changing a method in the child class
2. Parent classB. When one class gets data and actions from another
3. Child classC. The class being inherited from
4. OverrideD. The class that inherits
5. PolymorphismE. “Many forms”

Answers: 1-B, 2-C, 3-D, 4-A, 5-E

🧩 Scenario-based Exercises

  1. You have a class Animal. You want to create a class Dog that inherits from it. How do you write it? (class Dog(Animal):)
  2. You want Dog to have a bark() method. Where do you add it? (In the Dog class)
  3. You want Dog to speak differently from Animal. What do you do? (Override the speak() method)
  4. You want to call the parent’s __init__ from the child. What do you use? (super().__init__())
  5. You have a list of different animals. You want each to speak. What do you do? (Loop and call speak())

👥 Group Activity

Title: Build a Family of Classes

Instructions: In groups of 3, choose a parent class (e.g., Vehicle, Animal, Person). Create two child classes. Add at least one new method and override one method. Create objects and call the methods. Present to the class.

🧑 Individual Activity

Title: My First Inheritance

Instructions: Write a parent class called Shape with a method area(). Create two child classes: Circle and Square. Override area() in each. Create objects and call area(). Write down what happens.

🛠️ Mini Project

Title: A Zoo Program

Instructions: Create a parent class Animal with name and age. Create child classes Dog, Cat, and Cow. Override speak() in each. Create a list of animals. Loop through the list and call speak() and eat(). Print the results.

📋 Practical Assignment

Task: Write a short paragraph (5 sentences) explaining what you learned about inheritance and polymorphism. Then, list three things you found easy and one thing you found hard. Finally, describe the parent class and child classes you created.

🔑 Key Takeaways

  • Inheritance lets one class get data and methods from another.
  • Parent class is inherited from. Child class inherits.
  • Use inheritance for “is-a” relationships.
  • Override means changing a method in the child.
  • super() calls the parent’s method.
  • Polymorphism means “many forms”.
  • Same action, different results.
  • Inheritance and polymorphism work together.
  • Use inheritance wisely.

💬 Classroom Discussion Questions

  1. Why is inheritance useful?
  2. What is the difference between a parent class and a child class?
  3. What does “is-a” relationship mean?
  4. How does polymorphism make programs flexible?
  5. What would you build with inheritance and polymorphism?

➡️ Preparation for the Next Module

In Module Four, we will learn about encapsulation and abstraction. You will learn how to hide data and show only what is needed. You will learn how to protect your objects. To get ready, make sure you:

  • Understand inheritance and polymorphism.
  • Know how to create parent and child classes.
  • Know how to override methods.
  • Have practised writing your own inheritance examples.

See you in Module Four! 🚀


End of Module Three · Object Oriented Programming

5

Module Four

Module Four · Object Oriented Programming

📘 Module Four: Encapsulation and Abstraction – Protecting and Simplifying Your Code

🌟 Module Introduction

Welcome back, programmer! In Module One, you learned what Object Oriented Programming is. In Module Two, you learned how to write classes and create objects in Python. In Module Three, you learned about inheritance and polymorphism. You learned how one class can inherit from another and how different objects can respond to the same action in their own way.

Now imagine you have built a program with many classes. Your objects have data and methods. But what if someone changes the data in a way that breaks the program? What if someone sets a bank account balance to a negative number? What if someone changes the speed of a car to a million kilometres per hour? That would be a problem.

This is where encapsulation comes in. Encapsulation means keeping data safe inside an object. You hide the data and only allow changes through special methods. This protects your data from mistakes.

We will also learn about abstraction. Abstraction means showing only what is important and hiding the complicated details. When you drive a car, you use the steering wheel and pedals. You do not need to know how the engine works. That is abstraction.

By the end of this module, you will be able to protect your data and simplify your code. You will understand two more pillars of OOP. Let’s begin!

🎯 Learning Objectives

After you finish this module, you will be able to:

  • Explain what encapsulation is.
  • Explain why encapsulation is important.
  • Understand public and private attributes.
  • Use getters and setters to access and change data.
  • Use name mangling in Python.
  • Explain what abstraction is.
  • Understand why abstraction is important.
  • Create abstract classes and methods.
  • Use the abc module in Python.
  • Understand the difference between encapsulation and abstraction.
  • Avoid common mistakes with encapsulation and abstraction.
  • Feel confident to protect and simplify your own code.

📖 Warm-up Story: Ngozi and the Bank Account

Ngozi lived in Enugu. Her mother worked at a bank. One day, Ngozi asked her mother, “Mama, how do you keep people’s money safe? What if someone just walks in and changes the balance in the computer?”

Her mother smiled. “That is a good question,” she said. “The balance is private. No one can change it directly. If you want to deposit money, you must use the deposit method. If you want to withdraw, you must use the withdraw method. The withdraw method checks if you have enough money. If you do not, it says no.”

Ngozi understood. “So the balance is hidden,” she said. “And you can only change it through special methods that check the rules.”

“Exactly!” said her mother. “That is called encapsulation. We protect the data by hiding it. We only allow changes through safe methods.”

Ngozi was curious. “And what about the customer? They do not see all the complicated bank rules. They just use the ATM.”

Her mother nodded. “That is abstraction. We show the customer only what they need. They press buttons. They do not need to know how the bank’s computers work.”

Ngozi decided that day that she would learn about encapsulation and abstraction. And that is exactly what you will do in this module.

Moral of the story: Encapsulation protects data. Abstraction hides complicated details. Both make programs safer and easier to use.

📚 Main Lessons

Lesson 1: What is Encapsulation?

Definition: Encapsulation is the practice of keeping data safe inside an object. You hide the data and only allow changes through special methods.

Why it is important: It protects data from mistakes and misuse. It keeps your program safe.

Simple explanation: Think of a medicine bottle. The medicine is inside. You cannot just take it out. You must open the cap in the right way. That is encapsulation.

Real-life example: A bank account balance is private. You cannot change it directly. You must use deposit or withdraw.

School example: Your test score is private. The teacher enters it. You cannot change it yourself.

Home example: The money in your piggy bank is private. You must break the piggy bank to get it.

Nigerian example: The goods in a market stall are private. The trader brings them out when you want to buy.

Illustration:

  +---------------------+
  |  OBJECT: BankAccount|
  |  Private: balance   |
  |  Public: deposit()  |
  |  Public: withdraw() |
  +---------------------+
  You cannot change balance directly.
  You must use deposit() or withdraw().
  

Mini summary: Encapsulation keeps data safe. You hide the data and use special methods to change it.

Lesson 2: Public and Private Attributes

Definition: Public attributes can be accessed from anywhere. Private attributes can only be accessed inside the class.

Why it is important: You need to know which data to hide and which to show.

Simple explanation: Public means everyone can see it. Private means only the class can see it.

Real-life example: Your name is public. Your password is private.

School example: Your name is public. Your test score is private.

Home example: The front door of your house is public. Your bedroom is private.

Nigerian example: The signboard of a shop is public. The account book is private.

Illustration:

  Public: name
  Private: balance

  You can say: my_account.name
  You cannot say: my_account.balance
  

Mini summary: Public attributes are open to everyone. Private attributes are hidden. Use private for sensitive data.

Lesson 3: Creating Private Attributes in Python

Definition: In Python, you create a private attribute by starting its name with two underscores.

Why it is important: This tells other programmers: “Do not touch this directly.”

Simple explanation: You write self.__balance instead of self.balance.

Real-life example: A bank vault is locked. You need special access.

School example: The exam papers are locked in the principal’s office.

Home example: The medicine cabinet is locked. You need a key.

Nigerian example: The chief’s palace has a private room. Visitors cannot enter.

Example code:

  class BankAccount:
      def __init__(self, owner, balance):
          self.owner = owner          # public
          self.__balance = balance    # private

      def show_balance(self):
          print("Balance: " + str(self.__balance))
  

Illustration:

  self.owner = "Ada"       # public
  self.__balance = 1000    # private
       |
       V
  Only the class can access __balance
  

Mini summary: In Python, private attributes start with two underscores. They cannot be accessed from outside the class.

Lesson 4: Getters and Setters

Definition: A getter is a method that returns the value of a private attribute. A setter is a method that changes the value safely.

Why it is important: They let you control how data is accessed and changed.

Simple explanation: A getter says “here is the value”. A setter says “I will change the value, but only if it is safe”.

Real-life example: A bank teller can tell you your balance (getter) and can deposit money (setter).

School example: A teacher can tell you your score (getter) and can change it after remarking (setter).

Home example: A parent can tell you the WiFi password (getter) and can change it (setter).

Nigerian example: A trader can tell you the price (getter) and can change it during bargaining (setter).

Example code:

  class BankAccount:
      def __init__(self, owner, balance):
          self.owner = owner
          self.__balance = balance

      def get_balance(self):
          return self.__balance

      def set_balance(self, amount):
          if amount >= 0:
              self.__balance = amount
          else:
              print("Error: Balance cannot be negative.")

      def deposit(self, amount):
          if amount > 0:
              self.__balance += amount
              print("Deposited: " + str(amount))
          else:
              print("Error: Deposit must be positive.")

      def withdraw(self, amount):
          if amount > 0 and amount <= self.__balance:
              self.__balance -= amount
              print("Withdrawn: " + str(amount))
          else:
              print("Error: Invalid withdrawal.")
  

Illustration:

  get_balance() -> returns balance
  set_balance() -> changes balance if safe
  deposit() -> adds money if positive
  withdraw() -> removes money if enough
  

Mini summary: Getters return private data. Setters change private data safely. They protect your data.

Lesson 5: Why Encapsulation Matters

Definition: Encapsulation matters because it keeps your program safe and organised.

Why it is important: Without encapsulation, anyone can change your data and break your program.

Simple explanation: Imagine a car. You can press the accelerator to go faster. But you cannot directly change the engine speed. The car protects you from making dangerous changes.

Real-life example: A microwave has a door. You cannot run it with the door open. It protects you.

School example: A school has a gate. You cannot just walk in. You must sign in at the office.

Home example: A fridge has a door. You cannot change the temperature by touching the cooling system.

Nigerian example: A bank has a security guard. You cannot just walk into the vault.

Illustration:

  Without Encapsulation:
  balance = -5000  (BAD!)

  With Encapsulation:
  withdraw(5000) -> checks balance first
  

Mini summary: Encapsulation protects data. It stops mistakes and keeps your program safe.

Lesson 6: What is Abstraction?

Definition: Abstraction means showing only what is important and hiding the complicated details.

Why it is important: It makes things easier to use. You do not need to know how everything works.

Simple explanation: When you drive a car, you use the steering wheel and pedals. You do not need to know how the engine works. That is abstraction.

Real-life example: When you use a phone, you press buttons. You do not need to know how the screen works.

School example: When you write with a pen, you do not need to know how the ink flows.

Home example: When you use a TV remote, you press buttons. You do not need to know how the signal works.

Nigerian example: When you buy food from a trader, you do not need to know how the food was cooked.

Illustration:

  +---------------------+
  |  CAR                |
  |  Steering wheel     |
  |  Pedals             |
  |  (Engine hidden)    |
  +---------------------+
  You use the car without knowing the engine.
  

Mini summary: Abstraction hides complicated details. It shows only what you need to use.

Lesson 7: Abstract Classes

Definition: An abstract class is a class that cannot be used to create objects directly. It is meant to be inherited from.

Why it is important: It defines a common blueprint for other classes.

Simple explanation: An abstract class says: “All my children must have these methods.” But it does not say how those methods work.

Real-life example: A “Vehicle” abstract class says all vehicles must have a move method. But cars move differently from boats.

School example: A “Person” abstract class says all people must have a study method. But students study differently.

Home example: An “Appliance” abstract class says all appliances must have a work method. But fridges work differently from fans.

Nigerian example: A “Trader” abstract class says all traders must have a sell method. But food traders sell differently from cloth traders.

Illustration:

  Abstract Class: Vehicle
       |
       V
  Must have: move()
       |
       V
  +--------+ +--------+ +--------+
  | Car    | | Boat   | | Plane  |
  | move() | | move() | | move() |
  +--------+ +--------+ +--------+
  

Mini summary: An abstract class is a blueprint that cannot be used directly. It defines what child classes must have.

Lesson 8: Creating Abstract Classes in Python

Definition: In Python, you use the abc module to create abstract classes.

Why it is important: It enforces rules. Child classes must implement abstract methods.

Simple explanation: You import ABC and abstractmethod. You write @abstractmethod above the method.

Real-life example: A school says all students must wear a uniform. The uniform design is abstract.

School example: A teacher says all projects must have a cover page. The cover page is abstract.

Home example: A recipe says all cakes must have flour. The flour is abstract.

Nigerian example: A tailor says all dresses must have sleeves. The sleeves are abstract.

Example code:

  from abc import ABC, abstractmethod

  class Vehicle(ABC):
      @abstractmethod
      def move(self):
          pass

  class Car(Vehicle):
      def move(self):
          print("Car is driving.")

  class Boat(Vehicle):
      def move(self):
          print("Boat is sailing.")

  # my_vehicle = Vehicle()  # ERROR! Cannot create object
  my_car = Car()
  my_car.move()  # Car is driving.
  

Illustration:

  from abc import ABC, abstractmethod
       |
       V
  class Vehicle(ABC):
      @abstractmethod
      def move(self):
          pass
       |
       V
  Child classes MUST implement move()
  

Mini summary: In Python, abstract classes use ABC and @abstractmethod. Child classes must implement abstract methods.

Lesson 9: Encapsulation vs Abstraction

Definition: Encapsulation protects data. Abstraction hides complexity.

Why it is important: They are different but work together.

Simple explanation: Encapsulation is about safety. Abstraction is about simplicity.

Real-life example: A bank vault is encapsulation (safe). The ATM is abstraction (simple to use).

School example: The principal’s office is encapsulation (private). The school timetable is abstraction (simple to read).

Home example: The medicine cabinet is encapsulation (locked). The TV remote is abstraction (simple buttons).

Nigerian example: The bank vault is encapsulation (safe). The ATM is abstraction (easy to use).

Table: Encapsulation vs Abstraction

FeatureEncapsulationAbstraction
What it doesProtects dataHides complexity
FocusSafetySimplicity
HowPrivate attributes, getters, settersAbstract classes, methods
ExampleBank balanceCar steering wheel

Mini summary: Encapsulation protects data. Abstraction hides complexity. Both make programs better.

Lesson 10: Using Properties in Python

Definition: A property is a special way to use getters and setters in Python. It looks like an attribute but uses methods.

Why it is important: It makes your code cleaner and easier to read.

Simple explanation: You use @property for the getter and @name.setter for the setter.

Real-life example: You ask for “balance” and the bank tells you. You say “set balance to 500” and the bank checks first.

School example: You ask for “score” and the teacher tells you. You say “set score to 90” and the teacher checks.

Home example: You ask for “temperature” and the fridge tells you. You say “set temperature to 5” and the fridge checks.

Nigerian example: You ask for “price” and the trader tells you. You say “set price to 200” and the trader checks.

Example code:

  class BankAccount:
      def __init__(self, owner, balance):
          self.owner = owner
          self.__balance = balance

      @property
      def balance(self):
          return self.__balance

      @balance.setter
      def balance(self, amount):
          if amount >= 0:
              self.__balance = amount
          else:
              print("Error: Balance cannot be negative.")

  account = BankAccount("Ada", 1000)
  print(account.balance)  # 1000
  account.balance = 2000  # OK
  account.balance = -500  # Error
  

Illustration:

  @property
  def balance(self):
      return self.__balance
       |
       V
  account.balance -> calls getter

  @balance.setter
  def balance(self, amount):
      if amount >= 0:
          self.__balance = amount
       |
       V
  account.balance = 2000 -> calls setter
  

Mini summary: Properties make getters and setters look like attributes. They keep your code clean.

Lesson 11: Real-World Example – A Student Class

Definition: You can use encapsulation and abstraction together in a real program.

Why it is important: It shows how these ideas work in practice.

Simple explanation: You create a Student class with private scores. You add methods to add scores and get the average.

Real-life example: A school management system tracks student scores.

School example: A teacher uses a program to record and calculate scores.

Home example: A parent tracks their child’s progress.

Nigerian example: A school in Lagos uses a program to manage student results.

Example code:

  class Student:
      def __init__(self, name):
          self.name = name
          self.__scores = []

      def add_score(self, score):
          if 0 <= score <= 100:
              self.__scores.append(score)
          else:
              print("Error: Score must be between 0 and 100.")

      def get_average(self):
          if len(self.__scores) == 0:
              return 0
          return sum(self.__scores) / len(self.__scores)

      def show_scores(self):
          print(self.name + "'s scores: " + str(self.__scores))

  ada = Student("Ada")
  ada.add_score(85)
  ada.add_score(90)
  ada.add_score(78)
  ada.show_scores()
  print("Average: " + str(ada.get_average()))
  

Output:

  Ada's scores: [85, 90, 78]
  Average: 84.33333333333333
  

Illustration:

  Student
     |
     V
  Private: __scores
  Public: add_score(), get_average(), show_scores()
  

Mini summary: You can use encapsulation to protect scores and methods to work with them safely.

Lesson 12: Real-World Example – A Shape Abstract Class

Definition: You can use abstraction to define a common blueprint for shapes.

Why it is important: It shows how abstraction works in practice.

Simple explanation: You create an abstract Shape class with an abstract area method. Then Circle, Square, and Triangle implement it.

Real-life example: A drawing program calculates areas of different shapes.

School example: A maths program calculates areas.

Home example: A garden planner calculates areas of plots.

Nigerian example: A land surveyor calculates areas of plots.

Example code:

  from abc import ABC, abstractmethod
  import math

  class Shape(ABC):
      @abstractmethod
      def area(self):
          pass

  class Circle(Shape):
      def __init__(self, radius):
          self.radius = radius

      def area(self):
          return math.pi * self.radius ** 2

  class Square(Shape):
      def __init__(self, side):
          self.side = side

      def area(self):
          return self.side ** 2

  class Triangle(Shape):
      def __init__(self, base, height):
          self.base = base
          self.height = height

      def area(self):
          return 0.5 * self.base * self.height

  shapes = [Circle(5), Square(4), Triangle(6, 3)]

  for shape in shapes:
      print("Area: " + str(shape.area()))
  

Output:

  Area: 78.53981633974483
  Area: 16
  Area: 9.0
  

Illustration:

  Abstract Shape
       |
       V
  +--------+ +--------+ +--------+
  | Circle | | Square | |Triangle|
  | area() | | area() | | area() |
  +--------+ +--------+ +--------+
  

Mini summary: Abstract classes define a blueprint. Child classes implement the details.

Lesson 13: Common Mistakes with Encapsulation and Abstraction

Definition: These are mistakes beginners often make.

Why it is important: Knowing them helps you avoid them.

Simple explanation: Here are some mistakes to watch out for.

List of mistakes:

  • Making everything private. Some things should be public.
  • Forgetting to use getters and setters.
  • Not checking values in setters.
  • Trying to create an object from an abstract class.
  • Forgetting to implement abstract methods in child classes.
  • Using abstraction when it is not needed.

Illustration:

  Bad Code                Good Code
  +----------------+      +----------------+
  | self.balance   |      | self.__balance |
  | (public)       |      | (private)      |
  +----------------+      +----------------+
  

Mini summary: Avoid common mistakes. Use private only for sensitive data. Always implement abstract methods.

Lesson 14: Best Practices for Encapsulation and Abstraction

Definition: These are good habits to follow.

Why it is important: They make your code better.

Simple explanation: Here are some best practices.

List of best practices:

  • Keep sensitive data private.
  • Use getters and setters to control access.
  • Validate data in setters.
  • Use abstract classes for common blueprints.
  • Keep your code simple and clear.
  • Document your classes and methods.

Illustration:

  Best Practice:
  - Private data
  - Safe setters
  - Abstract blueprints
  - Clear names
  

Mini summary: Follow best practices. Protect data. Simplify complexity. Keep code clean.

Lesson 15: Putting It All Together – A Complete Program

Definition: You will now combine encapsulation and abstraction in one program.

Why it is important: This is how real OOP programs work.

Simple explanation: Create an abstract class. Create child classes. Use private data. Use getters and setters. Create objects and use them.

Real-life example: A payment system with different payment methods.

School example: A grading system with different subjects.

Home example: A smart home system with different appliances.

Nigerian example: A market system with different types of traders.

Example code:

  from abc import ABC, abstractmethod

  class Payment(ABC):
      def __init__(self, amount):
          self.__amount = amount

      @property
      def amount(self):
          return self.__amount

      @amount.setter
      def amount(self, value):
          if value > 0:
              self.__amount = value
          else:
              print("Error: Amount must be positive.")

      @abstractmethod
      def pay(self):
          pass

  class CardPayment(Payment):
      def pay(self):
          print("Paid " + str(self.amount) + " with card.")

  class CashPayment(Payment):
      def pay(self):
          print("Paid " + str(self.amount) + " with cash.")

  payments = [CardPayment(5000), CashPayment(2000)]

  for payment in payments:
      payment.pay()
  

Output:

  Paid 5000 with card.
  Paid 2000 with cash.
  

Illustration:

  Abstract Payment
       |
       V
  +-------------+ +-------------+
  | CardPayment | | CashPayment |
  | pay()       | | pay()       |
  +-------------+ +-------------+
  Private: __amount
  Public: amount (property), pay()
  

Mini summary: You can combine encapsulation and abstraction. Abstract classes define blueprints. Private data protects information.

📖 Key Vocabulary

WordSimple Definition
EncapsulationKeeping data safe inside an object.
Public attributeData that anyone can access.
Private attributeData that only the class can access.
GetterA method that returns private data.
SetterA method that changes private data safely.
PropertyA special way to use getters and setters in Python.
AbstractionHiding complicated details.
Abstract classA class that cannot be used directly. It is a blueprint.
Abstract methodA method that must be implemented by child classes.
ABCAbstract Base Class. A module in Python.
Name manglingHow Python makes attributes private.
ValidationChecking that data is correct.

🔑 Important Concepts

  • Encapsulation protects data: Use private attributes.
  • Getters and setters control access: They keep data safe.
  • Properties are clean: They look like attributes.
  • Abstraction hides complexity: Show only what is needed.
  • Abstract classes are blueprints: They define what child classes must have.
  • Child classes must implement abstract methods: This enforces rules.
  • Encapsulation and abstraction work together: Protect data and simplify code.

🧭 Step-by-Step Explanations

How to create a private attribute

  1. Use two underscores before the name: self.__balance.
  2. Access it only inside the class.
  3. Use getters and setters to access from outside.

How to create a getter and setter

  1. Write a method to return the value: def get_balance(self): return self.__balance.
  2. Write a method to change the value: def set_balance(self, amount): ....
  3. Check the value before changing it.

How to create an abstract class

  1. Import ABC and abstractmethod from abc.
  2. Write class MyClass(ABC):.
  3. Add @abstractmethod above methods.
  4. Child classes must implement these methods.

🌍 Real-life Examples

  • A bank account with private balance and deposit methods.
  • A car with a steering wheel (abstraction) and engine (encapsulation).
  • A phone with a screen (abstraction) and battery (encapsulation).
  • A student with private scores and methods to add scores.
  • A shape abstract class with circle, square, and triangle children.

🇳🇬 Nigerian Examples

  • A bank account with private balance and deposit/withdraw methods.
  • A market stall with private goods and buy/sell methods.
  • A danfo bus with private route and move/stop methods.
  • A student with private scores and add_score/get_average methods.
  • A trader abstract class with food and cloth trader children.

🎈 Fun Examples Children Can Relate To

  • A video game character with private health and take_damage/heal methods.
  • A toy car with private speed and accelerate/brake methods.
  • A pet with private hunger and feed/play methods.
  • A football with private pressure and kick/bounce methods.
  • A bicycle with private gear and pedal/brake methods.

🏠 Everyday Examples

  • Your phone with private battery and charge/use methods.
  • Your fridge with private temperature and cool/defrost methods.
  • Your TV with private volume and increase/decrease methods.
  • Your watch with private time and set_time methods.
  • Your school bag with private items and add/remove methods.

👨‍👩‍👧 Parent Tips

  • Explain encapsulation like a bank vault.
  • Explain abstraction like driving a car.
  • Ask your child to identify private and public things at home.
  • Help them write a simple class with private data.
  • Celebrate when they understand these concepts.

💡 Interesting Facts

  • Encapsulation is one of the four pillars of OOP.
  • Abstraction is another pillar of OOP.
  • Python uses name mangling for private attributes.
  • The abc module was added in Python 2.6.
  • Properties make Python code cleaner.

🤔 Did You Know?

  • Did you know that Python does not have true private attributes?
  • Did you know that name mangling is just a convention?
  • Did you know that abstract classes can have normal methods too?
  • Did you know that properties can have docstrings?
  • Did you know that encapsulation is used in almost every app?

📌 Remember This

  • Encapsulation protects data.
  • Public attributes are open. Private attributes are hidden.
  • Getters return data. Setters change data safely.
  • Properties make getters and setters look like attributes.
  • Abstraction hides complexity.
  • Abstract classes are blueprints.
  • Child classes must implement abstract methods.
  • Encapsulation and abstraction work together.

⚠️ Common Mistakes

  • Making everything private.
  • Forgetting to use getters and setters.
  • Not checking values in setters.
  • Trying to create an object from an abstract class.
  • Forgetting to implement abstract methods in child classes.
  • Using abstraction when it is not needed.

✅ Best Practices

  • Keep sensitive data private.
  • Use getters and setters to control access.
  • Validate data in setters.
  • Use abstract classes for common blueprints.
  • Keep your code simple and clear.
  • Document your classes and methods.

📊 Illustrations, Diagrams, and Tables

Flowchart: Encapsulation and Abstraction

  Create Class
        |
        V
  Add Private Data
        |
        V
  Add Getters/Setters
        |
        V
  Create Abstract Methods
        |
        V
  Create Child Classes
        |
        V
  Implement Methods
        |
        V
  Use Objects Safely! 🎉
  

Timeline: Your OOP Journey

  Module 1: What is OOP?
  Module 2: Classes and Objects
  Module 3: Inheritance and Polymorphism
  Module 4: Encapsulation and Abstraction
  Module 5: Putting It All Together
  

Table: Public vs Private

FeaturePublicPrivate
Who can access?AnyoneOnly the class
Python syntaxself.nameself.__name
ExampleNameBalance
Best forGeneral dataSensitive data

Comparison Table: Encapsulation vs Abstraction

FeatureEncapsulationAbstraction
What it doesProtects dataHides complexity
FocusSafetySimplicity
HowPrivate attributes, getters, settersAbstract classes, methods
ExampleBank balanceCar steering wheel

📝 Summary After Every Lesson

Lesson 1: Encapsulation keeps data safe inside an object.

Lesson 2: Public attributes are open. Private attributes are hidden.

Lesson 3: In Python, private attributes start with two underscores.

Lesson 4: Getters return data. Setters change data safely.

Lesson 5: Encapsulation protects data from mistakes.

Lesson 6: Abstraction hides complicated details.

Lesson 7: Abstract classes are blueprints for other classes.

Lesson 8: In Python, use ABC and @abstractmethod.

Lesson 9: Encapsulation protects data. Abstraction hides complexity.

Lesson 10: Properties make getters and setters look like attributes.

Lesson 11: You can use encapsulation to protect student scores.

Lesson 12: You can use abstraction to define a shape blueprint.

Lesson 13: Avoid common mistakes. Use private only for sensitive data.

Lesson 14: Follow best practices. Protect data. Simplify code.

Lesson 15: You can combine encapsulation and abstraction in one program.

📦 End-of-Module Summary

In this module, you learned about encapsulation and abstraction. You learned that encapsulation keeps data safe by hiding it and using getters and setters. You learned that abstraction hides complicated details and shows only what is needed. You learned how to create private attributes in Python. You learned how to use properties. You learned how to create abstract classes and methods using the abc module. You also learned the difference between encapsulation and abstraction and how they work together. You are now ready for Module Five, where you will put everything together in a complete project.

❓ Frequently Asked Questions (10 questions)

  1. What is encapsulation? Keeping data safe inside an object.
  2. What is a private attribute? Data that only the class can access.
  3. How do I create a private attribute in Python? Use two underscores before the name.
  4. What is a getter? A method that returns private data.
  5. What is a setter? A method that changes private data safely.
  6. What is abstraction? Hiding complicated details.
  7. What is an abstract class? A class that cannot be used directly. It is a blueprint.
  8. How do I create an abstract class in Python? Use ABC and @abstractmethod.
  9. What is the difference between encapsulation and abstraction? Encapsulation protects data. Abstraction hides complexity.
  10. What are common mistakes? Making everything private, forgetting to implement abstract methods.

🔗 Matching Exercises

Match the word to its meaning.

WordMeaning
1. EncapsulationA. A method that returns private data
2. GetterB. Keeping data safe inside an object
3. SetterC. A class that cannot be used directly
4. AbstractionD. A method that changes private data safely
5. Abstract classE. Hiding complicated details

Answers: 1-B, 2-A, 3-D, 4-E, 5-C

🧩 Scenario-based Exercises

  1. You want to protect a bank balance. What do you use? (Encapsulation with private attribute)
  2. You want to allow deposits but check for negative numbers. What do you use? (A setter with validation)
  3. You want to hide the complicated engine of a car. What do you use? (Abstraction)
  4. You want all shapes to have an area method. What do you use? (Abstract class)
  5. You want to access a private balance safely. What do you use? (A getter)

👥 Group Activity

Title: Protect and Simplify

Instructions: In groups of 3, choose a class (e.g., BankAccount, Student, Pet). Add private attributes. Add getters and setters. Add an abstract class. Create child classes. Present to the class.

🧑 Individual Activity

Title: My First Encapsulation

Instructions: Write a class called BankAccount with private balance. Add deposit, withdraw, and get_balance methods. Test with different amounts. Write down what happens.

🛠️ Mini Project

Title: A Complete Student Management System

Instructions: Create an abstract class Person with name and age. Create a child class Student with private scores. Add methods to add scores, get average, and show scores. Create multiple students. Test your program. Present to the class.

📋 Practical Assignment

Task: Write a short paragraph (5 sentences) explaining what you learned about encapsulation and abstraction. Then, list three things you found easy and one thing you found hard. Finally, describe the class you created and how it protects data.

🔑 Key Takeaways

  • Encapsulation protects data.
  • Private attributes are hidden.
  • Getters return data. Setters change data safely.
  • Properties make getters and setters look like attributes.
  • Abstraction hides complexity.
  • Abstract classes are blueprints.
  • Child classes must implement abstract methods.
  • Encapsulation and abstraction work together.
  • Follow best practices. Keep your code clean.

💬 Classroom Discussion Questions

  1. Why is encapsulation important?
  2. What is the difference between public and private attributes?
  3. How does abstraction make programs easier to use?
  4. What is an abstract class?
  5. What would you protect with encapsulation in your own program?

➡️ Preparation for the Next Module

In Module Five, we will learn about putting it all together. You will build a complete OOP program using classes, objects, inheritance, polymorphism, encapsulation, and abstraction. To get ready, make sure you:

  • Understand encapsulation and abstraction.
  • Know how to create private attributes.
  • Know how to use getters and setters.
  • Know how to create abstract classes.
  • Have practised writing your own classes.

See you in Module Five! 🚀


End of Module Four · Object Oriented Programming

6

Module FIve

Module Five · Object Oriented Programming

📘 Module Five: Putting It All Together – Building a Complete OOP Program

🌟 Module Introduction

Welcome back, programmer! You have come a long way. In Module One, you learned what Object Oriented Programming is. You learned about objects and classes. In Module Two, you learned how to write classes and create objects in Python. In Module Three, you learned about inheritance and polymorphism. In Module Four, you learned about encapsulation and abstraction.

Now it is time to put everything together. In this module, you will build a complete program using all the ideas you have learned. You will create classes. You will use inheritance. You will use polymorphism. You will protect data with encapsulation. You will simplify with abstraction.

We will build a School Management System. It will have students, teachers, and courses. It will show how OOP makes programs organised and powerful. By the end, you will have a complete program that you can run and be proud of.

We will keep using simple words and lots of examples. Let’s build something amazing!

🎯 Learning Objectives

After you finish this module, you will be able to:

  • Review all four pillars of OOP.
  • Plan a complete OOP program.
  • Create a parent class with common attributes and methods.
  • Create child classes with inheritance.
  • Override methods to create polymorphism.
  • Use encapsulation to protect data.
  • Use abstraction to simplify your design.
  • Combine all concepts in one program.
  • Test and debug your program.
  • Understand how OOP is used in real software.
  • Avoid common mistakes in large programs.
  • Feel proud of your complete OOP program.

📖 Warm-up Story: Emeka and the School Computer

Emeka lived in Abuja. His school had just received new computers. The principal asked Emeka to help create a program to manage student information. Emeka was excited. He had learned about OOP and wanted to use it.

He started by thinking about what a school has. A school has students. A school has teachers. A school has courses. Each of these is an object.

Emeka created a class called Person. It had a name and an age. Then he created a class called Student that inherited from Person. A student also has a class level and scores. Then he created a class called Teacher that also inherited from Person. A teacher also has a subject and a salary.

He used encapsulation to protect the student’s scores. He used abstraction to create a common blueprint for all people. He used polymorphism so that both students and teachers could introduce themselves in their own way.

When he finished, he showed the program to his principal. The principal was amazed. “This program can manage hundreds of students and teachers,” she said. “You have built something truly useful.”

Emeka smiled. He had learned that OOP is not just about writing code. It is about solving real problems in an organised way.

Moral of the story: OOP helps you build big programs by organising them into small, manageable objects.

📚 Main Lessons

Lesson 1: Reviewing the Four Pillars of OOP

Definition: The four pillars of OOP are encapsulation, abstraction, inheritance, and polymorphism.

Why it is important: These are the foundation of all OOP programs.

Simple explanation: Think of a house. Encapsulation is the walls. Abstraction is the door. Inheritance is the foundation. Polymorphism is the rooms that serve different purposes.

Real-life example: A car uses all four pillars. Encapsulation protects the engine. Abstraction hides the engine. Inheritance makes different car models from one design. Polymorphism makes different cars move differently.

School example: A school uses all four pillars. Encapsulation protects student records. Abstraction shows only the timetable. Inheritance creates different types of students. Polymorphism makes different students study differently.

Home example: A kitchen uses all four pillars. Encapsulation protects the fridge. Abstraction hides the cooking process. Inheritance creates different appliances from one design. Polymorphism makes different appliances work differently.

Nigerian example: A market uses all four pillars. Encapsulation protects the goods. Abstraction shows only the prices. Inheritance creates different types of traders. Polymorphism makes different traders sell differently.

Table: The Four Pillars

PillarWhat it doesExample
EncapsulationProtects dataPrivate bank balance
AbstractionHides complexityCar steering wheel
InheritanceReuses codeDog inherits Animal
PolymorphismMany formsDog barks, Cat meows

Mini summary: The four pillars of OOP are encapsulation, abstraction, inheritance, and polymorphism. They work together to make programs organised and powerful.

Lesson 2: Planning Your Program

Definition: Planning means deciding what classes you need and what they will do.

Why it is important: A good plan saves time and prevents confusion.

Simple explanation: Before you write code, think about the objects in your program. What are they? What data do they have? What actions can they do?

Real-life example: Before building a house, you draw a plan.

School example: Before writing an essay, you make an outline.

Home example: Before cooking, you gather ingredients.

Nigerian example: Before sewing a dress, you take measurements.

Illustration:

  Plan Your Program
        |
        V
  What objects do I need?
        |
        V
  What data do they have?
        |
        V
  What actions can they do?
        |
        V
  Start Coding!
  

Mini summary: Planning means deciding what classes you need. Think before you code.

Lesson 3: Designing the Parent Class – Person

Definition: A parent class holds common attributes and methods that child classes will share.

Why it is important: It saves time and keeps code organised.

Simple explanation: Both students and teachers are people. They both have names and ages. They both can introduce themselves. So we create a Person class.

Real-life example: All people have names and ages.

School example: All members of a school have names and ages.

Home example: All family members have names and ages.

Nigerian example: All Nigerians have names and ages.

Example code:

  class Person:
      def __init__(self, name, age):
          self.name = name
          self.age = age

      def introduce(self):
          print("Hello, my name is " + self.name + " and I am " + str(self.age) + " years old.")
  

Illustration:

  class Person:
      __init__ -> name, age
      introduce() -> "Hello, my name is..."
  

Mini summary: The Person class holds common data and actions for all people.

Lesson 4: Creating the Student Class

Definition: A student is a person who studies. The Student class inherits from Person.

Why it is important: Students have special data (class level, scores) and special actions (study, take exam).

Simple explanation: The Student class gets name and age from Person. It adds class level and scores.

Real-life example: A student has a name, age, class, and scores.

School example: A student in JSS3 has scores in different subjects.

Home example: A child in school has homework and test scores.

Nigerian example: A student in a Nigerian school takes WAEC exams.

Example code:

  class Student(Person):
      def __init__(self, name, age, class_level):
          super().__init__(name, age)
          self.class_level = class_level
          self.__scores = []

      def add_score(self, score):
          if 0 <= score <= 100:
              self.__scores.append(score)
          else:
              print("Error: Score must be between 0 and 100.")

      def get_average(self):
          if len(self.__scores) == 0:
              return 0
          return sum(self.__scores) / len(self.__scores)

      def study(self):
          print(self.name + " is studying.")

      def introduce(self):
          super().introduce()
          print("I am in " + self.class_level + ".")
  

Illustration:

  class Student(Person):
      __init__ -> name, age, class_level, __scores
      add_score() -> adds a score safely
      get_average() -> returns average
      study() -> "studying"
      introduce() -> calls parent + "I am in JSS3"
  

Mini summary: The Student class inherits from Person. It adds class level, scores, and study methods.

Lesson 5: Creating the Teacher Class

Definition: A teacher is a person who teaches. The Teacher class inherits from Person.

Why it is important: Teachers have special data (subject, salary) and special actions (teach, mark).

Simple explanation: The Teacher class gets name and age from Person. It adds subject and salary.

Real-life example: A teacher has a name, age, subject, and salary.

School example: A maths teacher teaches maths and marks exams.

Home example: A private tutor teaches at home.

Nigerian example: A teacher in a Nigerian school prepares students for exams.

Example code:

  class Teacher(Person):
      def __init__(self, name, age, subject, salary):
          super().__init__(name, age)
          self.subject = subject
          self.__salary = salary

      @property
      def salary(self):
          return self.__salary

      @salary.setter
      def salary(self, amount):
          if amount > 0:
              self.__salary = amount
          else:
              print("Error: Salary must be positive.")

      def teach(self):
          print(self.name + " is teaching " + self.subject + ".")

      def introduce(self):
          super().introduce()
          print("I teach " + self.subject + ".")
  

Illustration:

  class Teacher(Person):
      __init__ -> name, age, subject, __salary
      salary (property) -> getter and setter
      teach() -> "teaching"
      introduce() -> calls parent + "I teach Maths"
  

Mini summary: The Teacher class inherits from Person. It adds subject, salary, and teach methods.

Lesson 6: Creating the Course Class

Definition: A course is a subject that students take and teachers teach.

Why it is important: Courses connect students and teachers.

Simple explanation: A course has a name, a teacher, and a list of students.

Real-life example: A maths course has a teacher and many students.

School example: JSS3 Maths is a course with Mr Bello and 30 students.

Home example: A cooking class has a teacher and students.

Nigerian example: A WAEC preparation course has a teacher and students.

Example code:

  class Course:
      def __init__(self, name, teacher):
          self.name = name
          self.teacher = teacher
          self.students = []

      def add_student(self, student):
          self.students.append(student)
          print(student.name + " has been added to " + self.name + ".")

      def show_details(self):
          print("Course: " + self.name)
          print("Teacher: " + self.teacher.name)
          print("Students: " + str(len(self.students)))
  

Illustration:

  class Course:
      __init__ -> name, teacher, students
      add_student() -> adds a student
      show_details() -> prints course info
  

Mini summary: The Course class connects students and teachers. It has a name, a teacher, and a list of students.

Lesson 7: Using Inheritance and Polymorphism

Definition: Inheritance lets Student and Teacher share code from Person. Polymorphism lets them introduce themselves differently.

Why it is important: It makes the program flexible and organised.

Simple explanation: Both students and teachers can introduce themselves. But students say “I am in JSS3” and teachers say “I teach Maths”.

Real-life example: Both doctors and nurses are people. They introduce themselves differently.

School example: Both students and teachers are people. They introduce themselves differently.

Home example: Both children and parents are people. They introduce themselves differently.

Nigerian example: Both traders and customers are people. They introduce themselves differently.

Example code:

  people = [
      Student("Ada", 14, "JSS3"),
      Teacher("Mr Bello", 35, "Maths", 150000),
      Student("Tunde", 15, "JSS2"),
      Teacher("Mrs Okafor", 40, "English", 180000)
  ]

  for person in people:
      person.introduce()
      print("---")
  

Output:

  Hello, my name is Ada and I am 14 years old.
  I am in JSS3.
  ---
  Hello, my name is Mr Bello and I am 35 years old.
  I teach Maths.
  ---
  Hello, my name is Tunde and I am 15 years old.
  I am in JSS2.
  ---
  Hello, my name is Mrs Okafor and I am 40 years old.
  I teach English.
  ---
  

Illustration:

  for person in people:
      person.introduce()
       |
       V
  Student.introduce() -> "I am in JSS3"
  Teacher.introduce() -> "I teach Maths"
  

Mini summary: Inheritance shares code. Polymorphism lets each object respond in its own way.

Lesson 8: Using Encapsulation to Protect Data

Definition: Encapsulation protects sensitive data like scores and salary.

Why it is important: It prevents accidental changes and errors.

Simple explanation: Scores are private. You can only add them through the add_score method. Salary is private. You can only change it through the salary setter.

Real-life example: A bank protects your balance.

School example: A school protects student records.

Home example: A family protects private documents.

Nigerian example: A bank protects your account details.

Example code:

  ada = Student("Ada", 14, "JSS3")
  ada.add_score(85)
  ada.add_score(90)
  ada.add_score(78)

  # ada.__scores = [100, 100, 100]  # ERROR! Cannot access directly

  print("Ada's average: " + str(ada.get_average()))
  

Output:

  Ada's average: 84.33333333333333
  

Illustration:

  Private: __scores
  Public: add_score(), get_average()
       |
       V
  Scores are safe!
  

Mini summary: Encapsulation protects sensitive data. Use private attributes and safe methods.

Lesson 9: Using Abstraction to Simplify

Definition: Abstraction hides complicated details and shows only what is needed.

Why it is important: It makes your program easier to use.

Simple explanation: Users of your program do not need to know how scores are stored. They just call add_score and get_average.

Real-life example: When you drive a car, you do not need to know how the engine works.

School example: When you check your timetable, you do not need to know how it was made.

Home example: When you use a remote, you do not need to know how the TV works.

Nigerian example: When you use an ATM, you do not need to know how the bank’s computers work.

Example code:

  # The user does not need to know how scores are stored.
  # They just use add_score and get_average.

  ada = Student("Ada", 14, "JSS3")
  ada.add_score(85)
  ada.add_score(90)
  print("Average: " + str(ada.get_average()))
  

Illustration:

  User sees:
  add_score()
  get_average()

  User does not see:
  __scores list
  how average is calculated
  

Mini summary: Abstraction hides complexity. Users see only what they need.

Lesson 10: Building the Complete Program

Definition: You will now write the complete program.

Why it is important: This is the goal of the module.

Simple explanation: Put all the classes together. Create objects. Use methods. Print results.

Real-life example: A complete school management system.

School example: A program to manage students, teachers, and courses.

Home example: A program to manage family members and chores.

Nigerian example: A program to manage a Nigerian school.

Example code:

  class Person:
      def __init__(self, name, age):
          self.name = name
          self.age = age

      def introduce(self):
          print("Hello, my name is " + self.name + " and I am " + str(self.age) + " years old.")

  class Student(Person):
      def __init__(self, name, age, class_level):
          super().__init__(name, age)
          self.class_level = class_level
          self.__scores = []

      def add_score(self, score):
          if 0 <= score <= 100:
              self.__scores.append(score)
          else:
              print("Error: Score must be between 0 and 100.")

      def get_average(self):
          if len(self.__scores) == 0:
              return 0
          return sum(self.__scores) / len(self.__scores)

      def study(self):
          print(self.name + " is studying.")

      def introduce(self):
          super().introduce()
          print("I am in " + self.class_level + ".")

  class Teacher(Person):
      def __init__(self, name, age, subject, salary):
          super().__init__(name, age)
          self.subject = subject
          self.__salary = salary

      @property
      def salary(self):
          return self.__salary

      @salary.setter
      def salary(self, amount):
          if amount > 0:
              self.__salary = amount
          else:
              print("Error: Salary must be positive.")

      def teach(self):
          print(self.name + " is teaching " + self.subject + ".")

      def introduce(self):
          super().introduce()
          print("I teach " + self.subject + ".")

  class Course:
      def __init__(self, name, teacher):
          self.name = name
          self.teacher = teacher
          self.students = []

      def add_student(self, student):
          self.students.append(student)
          print(student.name + " has been added to " + self.name + ".")

      def show_details(self):
          print("Course: " + self.name)
          print("Teacher: " + self.teacher.name)
          print("Students: " + str(len(self.students)))

  # Create teachers
  mr_bello = Teacher("Mr Bello", 35, "Maths", 150000)
  mrs_okafor = Teacher("Mrs Okafor", 40, "English", 180000)

  # Create students
  ada = Student("Ada", 14, "JSS3")
  tunde = Student("Tunde", 15, "JSS2")
  ngozi = Student("Ngozi", 13, "JSS1")

  # Add scores
  ada.add_score(85)
  ada.add_score(90)
  ada.add_score(78)

  tunde.add_score(70)
  tunde.add_score(65)

  ngozi.add_score(95)
  ngozi.add_score(88)

  # Create courses
  maths = Course("Mathematics", mr_bello)
  english = Course("English", mrs_okafor)

  # Add students to courses
  maths.add_student(ada)
  maths.add_student(tunde)
  english.add_student(ada)
  english.add_student(ngozi)

  # Show all people
  print("=== PEOPLE ===")
  people = [ada, tunde, ngozi, mr_bello, mrs_okafor]
  for person in people:
      person.introduce()
      print("---")

  # Show course details
  print("=== COURSES ===")
  maths.show_details()
  english.show_details()

  # Show averages
  print("=== AVERAGES ===")
  print("Ada: " + str(ada.get_average()))
  print("Tunde: " + str(tunde.get_average()))
  print("Ngozi: " + str(ngozi.get_average()))
  

Output:

  Ada has been added to Mathematics.
  Tunde has been added to Mathematics.
  Ada has been added to English.
  Ngozi has been added to English.
  === PEOPLE ===
  Hello, my name is Ada and I am 14 years old.
  I am in JSS3.
  ---
  Hello, my name is Tunde and I am 15 years old.
  I am in JSS2.
  ---
  Hello, my name is Ngozi and I am 13 years old.
  I am in JSS1.
  ---
  Hello, my name is Mr Bello and I am 35 years old.
  I teach Maths.
  ---
  Hello, my name is Mrs Okafor and I am 40 years old.
  I teach English.
  ---
  === COURSES ===
  Course: Mathematics
  Teacher: Mr Bello
  Students: 2
  Course: English
  Teacher: Mrs Okafor
  Students: 2
  === AVERAGES ===
  Ada: 84.33333333333333
  Tunde: 67.5
  Ngozi: 91.5
  

Illustration:

  Person (parent)
       |
       V
  +-------------+ +-------------+
  | Student     | | Teacher     |
  | __scores    | | __salary    |
  | add_score() | | teach()     |
  | get_average()| | introduce() |
  +-------------+ +-------------+
       |                |
       V                V
  Course connects students and teachers
  

Mini summary: You built a complete school management system using all four pillars of OOP.

Lesson 11: Testing Your Program

Definition: Testing means running your program and checking for errors.

Why it is important: You want your program to work correctly.

Simple explanation: Run the program. Check the output. Try different inputs. Fix any problems.

Real-life example: Before a car is sold, it is tested on the road.

School example: Before an exam, you practise with past questions.

Home example: Before serving food, you taste it.

Nigerian example: Before a wedding, the family does a rehearsal.

Checklist:

  • Does the program run without errors?
  • Do all methods work?
  • Do the scores add correctly?
  • Do the averages calculate correctly?
  • Do the courses show the right students?

Illustration:

  Run Program
       |
       V
  Check Output
       |
       V
  Find Errors
       |
       V
  Fix Errors
       |
       V
  Run Again
       |
       V
  Works! 🎉
  

Mini summary: Always test your program. Check all parts. Fix any problems.

Lesson 12: Improving Your Program

Definition: Improving means making your program better.

Why it is important: Good programs can always be better.

Simple explanation: You can add more features. You can fix bugs. You can make the code cleaner.

Real-life example: A phone gets updates to add new features.

School example: A student improves their essay after getting feedback.

Home example: You improve a recipe after tasting it.

Nigerian example: A tailor improves a dress after the first fitting.

Ideas for improvement:

  • Add more types of people (e.g., Principal, Parent).
  • Add more courses.
  • Add a method to remove students from courses.
  • Add a method to show all scores for a student.
  • Add a method to calculate class average.
  • Add a method to save data to a file.

Illustration:

  Basic Program
       |
       V
  Add Features
       |
       V
  Fix Bugs
       |
       V
  Better Program!
  

Mini summary: You can always improve your program. Add features. Fix bugs. Make it better.

Lesson 13: OOP in Real Software

Definition: OOP is used in almost all modern software.

Why it is important: Knowing this helps you understand why you are learning OOP.

Simple explanation: Video games, banking apps, social media, and websites all use OOP.

Real-life example: In a game, each character is an object with health, speed, and actions.

School example: A school management system uses objects for students, teachers, and courses.

Home example: A smart home app uses objects for lights, fans, and doors.

Nigerian example: A bank app uses objects for customers, accounts, and transactions.

Illustration:

  Real Software
       |
       V
  +--------+ +--------+ +--------+
  | Game   | | Bank   | | Social |
  | objects| | objects| | objects|
  +--------+ +--------+ +--------+
  All use OOP!
  

Mini summary: OOP is used in games, banking, social media, and many other programs.

Lesson 14: Common Mistakes in Large Programs

Definition: These are mistakes beginners make when building big programs.

Why it is important: Knowing them helps you avoid them.

Simple explanation: Here are some mistakes to watch out for.

List of mistakes:

  • Not planning before coding.
  • Making classes too big.
  • Not using inheritance when it would help.
  • Forgetting to test parts of the program.
  • Not using encapsulation to protect data.
  • Having too many levels of inheritance.
  • Not commenting your code.

Illustration:

  Bad Program              Good Program
  +----------------+       +----------------+
  | One big class  |       | Many small     |
  | No plan        |       | classes        |
  | No tests       |       | Plan first     |
  +----------------+       +----------------+
  

Mini summary: Avoid common mistakes. Plan first. Use small classes. Test everything.

Lesson 15: Your Complete OOP Program – Review and Celebrate

Definition: You have built a complete OOP program.

Why it is important: Reviewing helps you remember.

Simple explanation: You used classes, objects, inheritance, polymorphism, encapsulation, and abstraction.

Real-life example: Like finishing a big project.

School example: Like finishing your final year project.

Home example: Like building a piece of furniture.

Nigerian example: Like completing a big tailoring job.

Illustration:

  Learn OOP
       |
       V
  Learn Classes & Objects
       |
       V
  Learn Inheritance & Polymorphism
       |
       V
  Learn Encapsulation & Abstraction
       |
       V
  Build Complete Program
       |
       V
  Celebrate 🎉
  

Mini summary: You built a complete OOP program. You are now an OOP programmer!

📖 Key Vocabulary

WordSimple Definition
EncapsulationKeeping data safe inside an object.
AbstractionHiding complicated details.
InheritanceWhen one class gets data and methods from another.
Polymorphism“Many forms” – different objects respond to the same action differently.
Parent classThe class being inherited from.
Child classThe class that inherits.
OverrideChanging a method in the child class.
super()A function that calls the parent’s method.
Private attributeData that only the class can access.
GetterA method that returns private data.
SetterA method that changes private data safely.
PropertyA special way to use getters and setters in Python.
Abstract classA class that cannot be used directly.
TestRunning a program to check for errors.

🔑 Important Concepts

  • Four pillars: Encapsulation, abstraction, inheritance, polymorphism.
  • Plan first: Think before you code.
  • Parent class: Holds common code.
  • Child class: Inherits and adds special code.
  • Polymorphism: Same action, different results.
  • Encapsulation: Protect data with private attributes.
  • Abstraction: Hide complexity.
  • Test everything: Find and fix errors.
  • Improve always: Make your program better.

🧭 Step-by-Step Explanations

How to plan a complete program

  1. List the objects you need.
  2. For each object, list its data (attributes).
  3. For each object, list its actions (methods).
  4. Find common data and actions. Put them in a parent class.
  5. Create child classes for special data and actions.
  6. Use encapsulation to protect sensitive data.
  7. Use polymorphism to let objects respond differently.

How to build the program

  1. Write the parent class.
  2. Write the child classes.
  3. Write any other classes (e.g., Course).
  4. Create objects.
  5. Call methods.
  6. Test the program.
  7. Fix any errors.
  8. Improve the program.

🌍 Real-life Examples

  • A school management system with students, teachers, and courses.
  • A hospital system with patients, doctors, and appointments.
  • A bank system with customers, accounts, and transactions.
  • A game with characters, weapons, and levels.
  • A shop with products, customers, and orders.

🇳🇬 Nigerian Examples

  • A Nigerian school management system with students, teachers, and courses.
  • A market system with traders, goods, and customers.
  • A bank system with customers, accounts, and transactions.
  • A transport system with buses, routes, and passengers.
  • A hospital system with patients, doctors, and appointments.

🎈 Fun Examples Children Can Relate To

  • A video game with heroes, enemies, and weapons.
  • A football team with players, coaches, and matches.
  • A pet shop with animals, owners, and toys.
  • A school with students, teachers, and classes.
  • A family with parents, children, and chores.

🏠 Everyday Examples

  • A phone with apps, contacts, and messages.
  • A kitchen with appliances, ingredients, and recipes.
  • A library with books, members, and loans.
  • A shop with products, customers, and orders.
  • A hospital with patients, doctors, and appointments.

👨‍👩‍👧 Parent Tips

  • Encourage your child to plan before coding.
  • Ask them to explain their program.
  • Help them test their program.
  • Celebrate when they finish their project.
  • Remind them that OOP is used in real software.

💡 Interesting Facts

  • OOP is used in almost all modern software.
  • Python is one of the most popular OOP languages.
  • Java is another popular OOP language.
  • OOP makes it easier to work in teams.
  • OOP makes it easier to fix bugs.

🤔 Did You Know?

  • Did you know that OOP was invented in the 1960s?
  • Did you know that the first OOP language was Simula?
  • Did you know that almost all apps use OOP?
  • Did you know that OOP makes code easier to reuse?
  • Did you know that you can build anything with OOP?

📌 Remember This

  • Four pillars: encapsulation, abstraction, inheritance, polymorphism.
  • Plan before you code.
  • Parent class holds common code.
  • Child class inherits and adds special code.
  • Polymorphism: same action, different results.
  • Encapsulation protects data.
  • Abstraction hides complexity.
  • Test everything.
  • Improve always.

⚠️ Common Mistakes

  • Not planning before coding.
  • Making classes too big.
  • Not using inheritance when it would help.
  • Forgetting to test parts of the program.
  • Not using encapsulation to protect data.
  • Having too many levels of inheritance.
  • Not commenting your code.

✅ Best Practices

  • Plan before you code.
  • Use small, focused classes.
  • Use inheritance for “is-a” relationships.
  • Use encapsulation to protect data.
  • Test each part of your program.
  • Comment your code.
  • Improve your program over time.

📊 Illustrations, Diagrams, and Tables

Flowchart: Building a Complete OOP Program

  Plan the Program
        |
        V
  Create Parent Class
        |
        V
  Create Child Classes
        |
        V
  Add Encapsulation
        |
        V
  Add Polymorphism
        |
        V
  Create Objects
        |
        V
  Test
        |
        V
  Improve
        |
        V
  Celebrate 🎉
  

Timeline: Your OOP Journey

  Module 1: What is OOP?
  Module 2: Classes and Objects
  Module 3: Inheritance and Polymorphism
  Module 4: Encapsulation and Abstraction
  Module 5: Complete Program
  Now: You are an OOP programmer!
  

Table: The Four Pillars in Our Program

PillarWhere UsedExample
EncapsulationStudent.__scores, Teacher.__salaryPrivate data
Abstractionadd_score(), get_average()Hidden complexity
InheritanceStudent(Person), Teacher(Person)Shared code
Polymorphismintroduce() in Student and TeacherDifferent results

Comparison Table: Without OOP vs With OOP

FeatureWithout OOPWith OOP
OrganisationMessyClean
ReuseHardEasy
Fixing bugsHardEasier
Adding featuresHardEasier
Working in teamsHardEasier

📝 Summary After Every Lesson

Lesson 1: The four pillars of OOP are encapsulation, abstraction, inheritance, and polymorphism.

Lesson 2: Plan your program before you code.

Lesson 3: The Person class holds common data for all people.

Lesson 4: The Student class inherits from Person and adds scores.

Lesson 5: The Teacher class inherits from Person and adds subject and salary.

Lesson 6: The Course class connects students and teachers.

Lesson 7: Inheritance shares code. Polymorphism lets objects respond differently.

Lesson 8: Encapsulation protects sensitive data.

Lesson 9: Abstraction hides complexity.

Lesson 10: You built a complete school management system.

Lesson 11: Always test your program.

Lesson 12: Improve your program over time.

Lesson 13: OOP is used in real software.

Lesson 14: Avoid common mistakes in large programs.

Lesson 15: You built a complete OOP program. You are an OOP programmer!

📦 End-of-Module Summary

In this module, you put everything together. You reviewed the four pillars of OOP: encapsulation, abstraction, inheritance, and polymorphism. You planned a complete program. You created a parent class called Person. You created child classes called Student and Teacher. You created a Course class. You used inheritance to share code. You used polymorphism to let objects introduce themselves differently. You used encapsulation to protect scores and salary. You used abstraction to hide complexity. You built a complete school management system. You tested it and learned how to improve it. You also learned how OOP is used in real software. You are now a complete OOP programmer!

❓ Frequently Asked Questions (10 questions)

  1. What are the four pillars of OOP? Encapsulation, abstraction, inheritance, polymorphism.
  2. Why should I plan before coding? To save time and avoid confusion.
  3. What is a parent class? A class that holds common data and methods.
  4. What is a child class? A class that inherits from a parent and adds special data and methods.
  5. What is polymorphism? Different objects responding to the same action in their own way.
  6. What is encapsulation? Protecting data with private attributes.
  7. What is abstraction? Hiding complexity and showing only what is needed.
  8. How do I test my program? Run it and check the output.
  9. How can I improve my program? Add features, fix bugs, make it cleaner.
  10. Where is OOP used? In games, banking, social media, and many other programs.

🔗 Matching Exercises

Match the word to its meaning.

WordMeaning
1. EncapsulationA. When one class gets data from another
2. AbstractionB. Protecting data
3. InheritanceC. Different objects respond differently
4. PolymorphismD. Hiding complexity
5. TestingE. Checking for errors

Answers: 1-B, 2-D, 3-A, 4-C, 5-E

🧩 Scenario-based Exercises

  1. You want to create a program about animals. What is the parent class? (Animal)
  2. You want dogs and cats to speak differently. What do you use? (Polymorphism)
  3. You want to protect a student’s scores. What do you use? (Encapsulation)
  4. You want to hide how scores are stored. What do you use? (Abstraction)
  5. You want to share common code between students and teachers. What do you use? (Inheritance)

👥 Group Activity

Title: Build a Complete Program Together

Instructions: In groups of 3, choose a topic (e.g., hospital, market, transport). Plan the classes. Create a parent class and child classes. Use encapsulation and polymorphism. Write the code together. Test it. Present to the class.

🧑 Individual Activity

Title: My First Complete OOP Program

Instructions: Write a program with a parent class called Shape and child classes Circle, Square, and Triangle. Use abstraction with an abstract area() method. Use polymorphism to call area() on all shapes. Write down what happens.

🛠️ Mini Project

Title: A Complete OOP Project

Instructions: Build a program for a small business (e.g., a shop, a restaurant, a library). Use all four pillars of OOP:

  • Create a parent class for common data.
  • Create child classes for different types.
  • Use encapsulation to protect sensitive data.
  • Use polymorphism to let objects behave differently.
  • Use abstraction to hide complexity.
Test your program. Present it to the class.

📋 Practical Assignment

Task: Write a short paragraph (5 sentences) explaining what you learned in this module. Then, list three things you found easy and one thing you found hard. Finally, describe your complete program and how it uses the four pillars of OOP.

🔑 Key Takeaways

  • The four pillars of OOP are encapsulation, abstraction, inheritance, and polymorphism.
  • Plan before you code.
  • Parent classes hold common code.
  • Child classes inherit and add special code.
  • Polymorphism lets objects respond differently.
  • Encapsulation protects data.
  • Abstraction hides complexity.
  • Always test your program.
  • Improve your program over time.
  • OOP is used in real software.

💬 Classroom Discussion Questions

  1. Why is planning important before coding?
  2. How do the four pillars of OOP work together?
  3. What is the benefit of using inheritance?
  4. How does encapsulation make programs safer?
  5. What would you build with OOP?

➡️ Preparation for the Next Module

Congratulations! You have completed all five modules of the Object Oriented Programming course. In the next steps, you can:

  • Build more complex programs with OOP.
  • Learn about design patterns.
  • Explore other OOP languages like Java or C#.
  • Contribute to open-source projects.
  • Teach others what you have learned.

You are now an OOP programmer. Go and build amazing things! 🚀


End of Module Five · Object Oriented Programming

🏆 Get Certified

🔒

Earn this certificate

Every lesson is already free to read. Sign up, pass the exam, and unlock Practice Tools plus a verified certificate with your name on it — ₦10,000/month.

🎓 Sign Up & Unlock for ₦4,000/month
🛠️ Practice Tools
Hands-on simulators & labs - subscription required.
→
🎯 Internship Tasks
Real-world tasks to build your portfolio - try them free for 7 days, no card required.
→