Advanced Programming II - SSS 3 Digital Technologies note
ADVANCED PROGRAMMING II
Subject: Digital Technologies
Class: SSS 3
Term: First Term
Week: 3
Topic: Advanced Programming II
Duration: 80 Minutes (Double Period)
1. Introduction
Programming enables us to develop applications that solve real-life problems. As software becomes more complex, programmers need methods for organising code, representing real-world entities and managing the relationships between different parts of a program.
In the previous lesson, we studied functions, parameters, return values, arrays and lists. In this lesson, we will study Object-Oriented Programming (OOP), which provides another way of organising programs.
Object-Oriented Programming is widely used in the development of school management systems, banking applications, games, mobile applications and other software products.
For example, a school management application may contain objects representing students, teachers, subjects and examination results. Each object can have its own data and related operations.
2. Meaning of Classes and Objects
2.1 Meaning of a Class
A class describes the common characteristics and actions associated with a category of objects.
For example, a school may have many students. Each student may have a name, age, admission number and examination scores. A class called Student can define these common characteristics and provide operations for working with student information.
2.2 Meaning of an Object
Using the student example, the class Student is the general blueprint, while Ada and Chidi can be represented as separate student objects with different names and admission numbers.
2.3 Examples of Classes and Objects
| Class | Possible Objects | Possible Characteristics |
|---|---|---|
| Student | Ada, Chidi, Musa | Name, age, admission number |
| Car | Toyota Corolla, Honda Civic | Colour, model, speed |
| BankAccount | Customer account A, Customer account B | Account number, balance |
| Book | Mathematics textbook, English textbook | Title, author, price |
2.4 Difference Between a Class and an Object
| Class | Object |
|---|---|
| Defines a structure or blueprint. | Is an instance created from a class. |
| Describes possible attributes and methods. | Has actual attribute values and can use the class's methods. |
Example: Student |
Example: a particular student named Ada. |
3. Basic Components of a Class
A class commonly contains attributes and methods.
3.1 Attributes
For a student object, attributes may include:
- Name
- Age
- Class level
- Admission number
- Examination score
3.2 Methods
Methods for a student-related class might include:
display_details()— displays student information.calculate_average()— calculates an average score.update_score()— updates an examination score.
Attributes describe an object's data, while methods describe operations that can be performed using that data.
4. Creating a Class in Python
Python uses the class keyword to define a class. The following example demonstrates a simple class.
class Student:
def display_message(self):
print("Welcome to Digital Technologies!")
student1 = Student()
student1.display_message()
Output:
Welcome to Digital Technologies!
Explanation:
class Student:defines a class namedStudent.display_message()is a method belonging to the class.selfrefers to the current instance of the class when the method is called on an object.student1 = Student()creates an object of the class.student1.display_message()calls the method using the object.
5. The Constructor and the __init__() Method
When creating objects, programmers often need to provide initial values for their attributes. In Python, the __init__() method is commonly used to initialise an object's attributes when an instance is created.
For example:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def display_details(self):
print("Name:", self.name)
print("Age:", self.age)
student1 = Student("Ada", 17)
student2 = Student("Chidi", 18)
student1.display_details()
student2.display_details()
Output:
Name: Ada
Age: 17
Name: Chidi
Age: 18
Explanation:
__init__()runs when a new instance is created, allowing its initial attributes to be set.nameandageare parameters supplied during object creation.self.nameandself.ageare attributes associated with the particular object.student1andstudent2are separate objects with different attribute values.
__init__() method is commonly called a constructor in introductory Python lessons. More precisely, it initialises an object; Python's __new__() method is responsible for creating the instance.
6. The Basic Principles of Object-Oriented Programming
Object-Oriented Programming is commonly explained through four major principles: encapsulation, inheritance, polymorphism and abstraction.
6.1 Encapsulation
Encapsulation helps organise related information and operations together. It can also help prevent inappropriate changes to an object's data.
Example: A bank account class may keep an account balance together with methods for depositing and withdrawing money. Instead of allowing every part of a program to change the balance arbitrarily, the program can provide methods that apply the appropriate rules.
class BankAccount:
def __init__(self, balance):
self.balance = balance
def deposit(self, amount):
if amount > 0:
self.balance += amount
def display_balance(self):
print("Balance:", self.balance)
account = BankAccount(5000)
account.deposit(2000)
account.display_balance()
Output:
Balance: 7000
This simple example groups the account balance and the deposit operation in one class. A production banking system would require stronger validation, access controls and security measures.
6.2 Inheritance
The class being inherited from is called the parent class or base class. The class that inherits from it is called the child class or derived class.
For example, a general Person class may define a person's name. A Student class can inherit that feature and add a student-specific attribute such as admission number.
class Person:
def __init__(self, name):
self.name = name
def introduce(self):
print("My name is", self.name)
class Student(Person):
def study(self):
print(self.name, "is studying.")
student1 = Student("Ada")
student1.introduce()
student1.study()
Output:
My name is Ada
Ada is studying.
The Student class inherits the introduce() method from Person and also defines its own study() method.
6.3 Polymorphism
For example, different types of animals can have a method named make_sound(), but each animal can produce a different sound.
class Dog:
def make_sound(self):
print("Bark")
class Cat:
def make_sound(self):
print("Meow")
animals = [Dog(), Cat()]
for animal in animals:
animal.make_sound()
Output:
Bark
Meow
The same method call, make_sound(), produces different results depending on the object receiving the call.
6.4 Abstraction
Abstraction makes systems easier to use because users can work with a simple interface without needing to understand every internal process.
Example: A person can use an ATM to withdraw money by following the displayed instructions. The user does not need to understand every internal banking and communication process involved.
In programming, abstraction can be implemented using suitable class designs, functions and, where appropriate, abstract classes or interfaces.
6.5 Summary of the Four Principles
| Principle | Meaning | Example |
|---|---|---|
| Encapsulation | Combines data and related methods and controls access to internal data. | A bank account class with deposit and withdrawal methods. |
| Inheritance | Allows one class to reuse or extend another class. | A Student class inheriting from Person. |
| Polymorphism | Allows a common interface to produce different behaviours for different objects. | Dog and Cat objects implementing make_sound(). |
| Abstraction | Hides unnecessary implementation details and exposes important features. | Using an ATM without knowing its internal processes. |
7. Advantages of Object-Oriented Programming
Object-Oriented Programming offers several advantages:
- Code reusability: Classes and inheritance can reduce the need to rewrite existing code.
- Modularity: A program can be divided into classes that handle different responsibilities.
- Maintainability: Organised code can be easier to understand, update and debug.
- Data organisation: Related data and operations can be grouped together.
- Extensibility: New classes and behaviours can be added as software requirements change.
- Real-world modelling: Objects can represent entities such as students, accounts, books and vehicles.
8. Applications of Object-Oriented Programming
OOP is used in many areas of software development.
| Application Area | Possible Use of OOP |
|---|---|
| School management systems | Representing students, teachers, classes and examination records. |
| Banking systems | Representing accounts, transactions and customers. |
| Video games | Representing characters, vehicles, objects and game actions. |
| E-commerce applications | Representing products, customers, shopping carts and orders. |
| Mobile applications | Organising application components, data and behaviours. |
| Library systems | Representing books, library members, loans and returns. |
9. Class Activity
Activity 1: Identify Classes and Objects
Consider a school library. Identify three possible classes and give two examples of objects for each class.
Activity 2: Create a Class
Using Python, create a class named Book with the attributes title and author. Create two objects and display their details.
Activity 3: Demonstrate Inheritance
Create a parent class named Person with a method that displays a person's name. Create a child class named Teacher that inherits from Person and adds a method called teach().
Activity 4: Identify OOP Principles
For each situation below, identify the most relevant OOP principle:
- A class controls how its internal data is changed.
- A new class reuses methods from an existing class.
- Different objects respond differently to the same method call.
- A user interacts with a simple interface without knowing the internal implementation.
10. Common Errors When Working with Classes and Objects
| Error | Explanation | Prevention |
|---|---|---|
| Incorrect indentation | Python uses indentation to define the body of a class and its methods. | Indent class and method statements correctly. |
| Forgetting self | An ordinary instance method usually needs self as its first parameter. |
Include self in instance method definitions. |
| Incorrect object creation | The class name may be used incorrectly when creating an instance. | Use the class name followed by parentheses, supplying any required arguments. |
| Misspelt attribute | The program may attempt to access an attribute that does not exist. | Check attribute names carefully. |
| Incorrect inheritance | A child class may not be defined with the intended parent class. | Place the parent class name in parentheses when defining the child class. |
11. Summary
In this lesson, we studied Object-Oriented Programming and its basic concepts.
- Object-Oriented Programming organises programs around objects.
- A class is a blueprint used to create objects.
- An object is an instance of a class.
- Attributes represent data, while methods define actions.
- Python uses the
classkeyword to define classes. - The
__init__()method is commonly used to initialise object attributes. - Encapsulation combines data and related methods while controlling access.
- Inheritance allows a class to reuse or extend another class.
- Polymorphism allows different objects to respond appropriately to a common interface.
- Abstraction hides unnecessary implementation details.
12. Evaluation Questions
- Define Object-Oriented Programming.
- Differentiate between a class and an object.
- Explain the meanings of attributes and methods.
- What is the purpose of the
__init__()method in Python? - Explain the four basic principles of Object-Oriented Programming.
- State four advantages of OOP.
- Give three examples of real-world applications of OOP.
- Write a simple Python program that defines a class named
Student, creates an object and displays the student's name.
13. Assignment
- Explain the difference between a class and an object, using a real-life example.
- Write a Python program that defines a
Carclass with the attributesbrandandcolour. Create two objects and display their details. - Explain encapsulation, inheritance, polymorphism and abstraction in your own words.
- Create a parent class named
Personand a child class namedStudent. Demonstrate inheritance in your program. - Describe four areas where Object-Oriented Programming can be applied.
14. Interactive Quiz
Answer all five questions and click Submit Quiz to see your score.
Comments
Post a Comment