Advanced Programming II - SSS 3 Digital Technologies note

Advanced Programming II - SSS 3 Digital Technologies

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.

Definition: Object-Oriented Programming (OOP) is a programming approach that organises software around objects, which combine data and the operations that work on that data.

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 is a blueprint or template used to define the data and behaviour that objects of a particular type can have.

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

An object is an individual instance of a class. It can contain its own data and use the behaviours defined by its class.

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

Attributes are variables associated with a class or its objects. They represent the data or characteristics of an object.

For a student object, attributes may include:

  • Name
  • Age
  • Class level
  • Admission number
  • Examination score

3.2 Methods

Methods are functions defined within a class. They describe actions or operations that objects of the class can perform.

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:

  1. class Student: defines a class named Student.
  2. display_message() is a method belonging to the class.
  3. self refers to the current instance of the class when the method is called on an object.
  4. student1 = Student() creates an object of the class.
  5. student1.display_message() calls the method using the object.
Remember: In Python, the name of a class conventionally begins with a capital letter, and the statements belonging to the class are indented.

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.
  • name and age are parameters supplied during object creation.
  • self.name and self.age are attributes associated with the particular object.
  • student1 and student2 are separate objects with different attribute values.
Note: The __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 is the practice of combining data and the methods that operate on it within a class, while controlling how the internal data is accessed or modified.

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

Inheritance is an OOP feature that allows a new class to reuse or extend attributes and methods from an existing class.

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

Polymorphism means that the same interface or method name can be used with different objects, producing behaviour appropriate to each object.

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 means presenting the important features of a system while hiding unnecessary implementation details from the user.

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:

  1. Code reusability: Classes and inheritance can reduce the need to rewrite existing code.
  2. Modularity: A program can be divided into classes that handle different responsibilities.
  3. Maintainability: Organised code can be easier to understand, update and debug.
  4. Data organisation: Related data and operations can be grouped together.
  5. Extensibility: New classes and behaviours can be added as software requirements change.
  6. 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:

  1. A class controls how its internal data is changed.
  2. A new class reuses methods from an existing class.
  3. Different objects respond differently to the same method call.
  4. 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 class keyword 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

  1. Define Object-Oriented Programming.
  2. Differentiate between a class and an object.
  3. Explain the meanings of attributes and methods.
  4. What is the purpose of the __init__() method in Python?
  5. Explain the four basic principles of Object-Oriented Programming.
  6. State four advantages of OOP.
  7. Give three examples of real-world applications of OOP.
  8. Write a simple Python program that defines a class named Student, creates an object and displays the student's name.

13. Assignment

  1. Explain the difference between a class and an object, using a real-life example.
  2. Write a Python program that defines a Car class with the attributes brand and colour. Create two objects and display their details.
  3. Explain encapsulation, inheritance, polymorphism and abstraction in your own words.
  4. Create a parent class named Person and a child class named Student. Demonstrate inheritance in your program.
  5. 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.

1. What is a class in Object-Oriented Programming?

2. What is an object?

3. Which OOP principle allows a child class to reuse or extend features of a parent class?

4. What is the main purpose of the __init__() method in a typical Python class?

5. Which principle allows different objects to respond differently to the same method call?

CMPNOTE | Digital Technologies Learning Resources

SSS 3 • First Term • Week 3

Comments

Popular posts from this blog

Complete Computer Studies/ICT Curriculum for JSS 1 to SSS 3

90 Objective Examination Questions in Major Subjects

Number Base System