📑 Contents

Chapter 20: Object-Oriented Programming & Programming Paradigms

9618 A Level Computer Science

Programming Paradigms Overview Low-Level Assembly Imperative Procedural Object-Oriented Java, Python Declarative SQL, Prolog OOP Pillars: Encapsulation | Inheritance | Polymorphism
📚 Learning Objectives
📋 Prior Knowledge Required
🌟 Did You Know?

Object-Oriented Programming was developed to help manage complexity in large software systems. The concept was first introduced with the Simula programming language in the 1960s and later popularised by Smalltalk. Today, OOP is one of the most widely used programming paradigms!

1. Programming Paradigms

A programming paradigm is a style or approach to programming that influences how programs are written, how problems are broken down, and how solutions are structured. Different paradigms are suited to different types of problems and systems.

Paradigm Description Key Characteristics Examples
Low-Level Closest to machine code, using mnemonics to directly control hardware Direct memory access, Register manipulation, Hardware-specific instructions x86 Assembly, ARM Assembly
Imperative (Procedural) Tells the computer how to perform tasks using sequences of commands Step-by-step instructions, Use of loops, conditions, Procedures/functions C, Pascal, Python (procedural)
Object-Oriented Models real-world entities using objects that combine data and behaviour Classes and objects, Encapsulation, Inheritance, Polymorphism Java, C++, Python (OOP)
Declarative Describes what should be done, not how to do it Rule-based or logic-based, No explicit control flow, Focus on outcomes SQL, Prolog, Haskell
IMPERATIVE APPROACH "HOW to do it" Step 1 → Step 2 → Step 3 → Result Explicit control flow, loops, conditions DECLARATIVE APPROACH "WHAT you want" Describe result → System figures it out Facts, rules, queries vs

1.1 Strengths and Weaknesses

Paradigm Strengths Weaknesses
Procedural Clear flow of control (top to bottom)
Efficient for simple tasks
Easy to implement algorithms
Becomes hard to manage in large programs
Poor modularity can lead to redundancy
Not ideal for complex state-based systems
Object-Oriented Enhances modularity with encapsulation
Real-world modelling via objects
Code reuse through inheritance
Polymorphism for flexible interfaces
Can become overly complex
Slower due to object overhead
Misuse leads to bloated hierarchies
Not ideal for every problem
Low-Level (Assembly) Complete control over hardware
Highly optimised for performance
Transparent view of machine operations
Steep learning curve
Hardware-specific, not portable
Manual memory management is error-prone
Difficult to debug/scale
Declarative Focuses on result rather than process
Concise and expressive
Suitable for complex logic or rule-based problems
Harder to learn for beginners
Less control over program flow
Not suited for all types of problems
Debugging can be challenging
💡 Exam Tip

When comparing paradigms in exams, always mention specific strengths AND weaknesses. Use the phrase "trade-off" when discussing the balance between control (low-level) and ease of use (high-level).

2. Low-Level Programming

Machine code and assembly language are examples of low-level languages. They provide direct control over hardware but require understanding of processor architecture and memory management.

2.1 Addressing Modes

Addressing modes determine how the processor locates data for an instruction. Understanding these is essential for writing effective assembly code.

📝 Immediate Addressing

Syntax: LOAD #value

Meaning: Load a constant value directly into the accumulator

Example: LOAD #5 ; Load the constant value 5 into the accumulator ADD #3 ; Add 3 to the accumulator STORE 200 ; Store result at memory address 200

Use when you want to work with literal values, not data in memory.

📝 Direct Addressing

Syntax: LOAD address

Meaning: Load the value stored at the specified memory address

Example: LOAD 100 ; Load the value stored at memory address 100 ADD 101 ; Add the value at address 101 STORE 102 ; Store result in address 102

Use when the data is stored at known memory addresses.

📝 Indirect Addressing

Syntax: LOAD @address

Meaning: The address given points to another address, where the data is stored

Example: ; Memory[150] = 300 ; Memory[300] = 42 LOAD @150 ; loads 42 into the accumulator

Use when data is stored in dynamically referenced locations.

IMMEDIATE LOAD #5 Value in instruction DIRECT LOAD 100 Address → Data INDIRECT LOAD @150 Address → Address → Data INDEXED LOAD 500[X] Base + Index offset RELATIVE BRANCH +3 Current + offset
📝 Indexed Addressing

Syntax: LOAD base[X]

Meaning: Load from base address + index register value

Example: LOAD 500[X] ; Load value from address (500 + contents of X) ADD 501[X] ; Add value from another offset ; If X = 2, this accesses addresses 502 and 503

Use for working with arrays or tables, where the index changes.

📝 Relative Addressing

Syntax: BRANCH offset

Meaning: Jump to a new instruction relative to the current instruction

Example: LOOP: LOAD #1 SUB 200 BRZ END ; If accumulator is zero, skip to END BR -3 ; Loop back to LOOP END: HALT

Use for loops and conditional branches without needing absolute addresses.

3. Imperative (Procedural) Programming

Imperative programming tells the computer how to perform tasks using sequences of commands. High-level languages such as Python, Java, and Visual Basic support the imperative style. Code can be made more organised by using structured programming principles.

3.1 Basic Imperative Approach

The basic imperative approach uses global variables and top-down sequential flow without procedures or functions.

Pseudocode - Temperature Conversion (No Procedures) // Global variables DECLARE inputTemp : REAL DECLARE convertedTemp : REAL DECLARE choice : INTEGER OUTPUT "Select conversion type:" OUTPUT "1. Celsius to Fahrenheit" OUTPUT "2. Fahrenheit to Celsius" OUTPUT "3. Celsius to Kelvin" INPUT choice OUTPUT "Enter the temperature:" INPUT inputTemp IF choice = 1 THEN SET convertedTemp = (inputTemp * 9 / 5) + 32 OUTPUT "Temperature in Fahrenheit: ", convertedTemp ELSE IF choice = 2 THEN SET convertedTemp = (inputTemp - 32) * 5 / 9 OUTPUT "Temperature in Celsius: ", convertedTemp ELSE IF choice = 3 THEN SET convertedTemp = inputTemp + 273.15 OUTPUT "Temperature in Kelvin: ", convertedTemp ELSE OUTPUT "Invalid option selected." ENDIF
❌ Problems with Basic Imperative

3.2 Structured (Procedural) Programming

Structured programming improves code organisation by using procedures and functions, local variables, and modular logic.

Pseudocode - Temperature Conversion (With Procedures) // Global variable for communication DECLARE choice : INTEGER PROCEDURE main() OUTPUT "Select conversion type:" OUTPUT "1. Celsius to Fahrenheit" OUTPUT "2. Fahrenheit to Celsius" OUTPUT "3. Celsius to Kelvin" INPUT choice IF choice = 1 THEN CALL convertCtoF() ELSE IF choice = 2 THEN CALL convertFtoC() ELSE IF choice = 3 THEN CALL convertCtoK() ELSE OUTPUT "Invalid option selected." ENDIF ENDPROCEDURE PROCEDURE convertCtoF() DECLARE inputTemp : REAL // Local variable DECLARE result : REAL // Local variable OUTPUT "Enter temperature in Celsius:" INPUT inputTemp SET result = (inputTemp * 9 / 5) + 32 OUTPUT "Temperature in Fahrenheit: ", result ENDPROCEDURE // Start program CALL main()
main() convertCtoF() convertFtoC() convertCtoK() Each procedure has LOCAL variables Code is MODULAR and REUSABLE
Feature Basic Imperative Structured (Procedural)
Reusability No reuse Easy to reuse procedures
Modularity All logic in one block Code divided into named units
Readability Can become unclear in longer code Easier to understand each part
Variables All global Mix of global and local
Maintenance Changes affect entire block Easier to update specific parts
💡 Exam Tip

The key difference between basic imperative and structured programming is modularity. Structured programming uses procedures/functions to break code into manageable, reusable pieces with local variables.

4. Classes (Object-Oriented Programming)

A class is a blueprint used to create objects in Object-Oriented Programming (OOP). It defines a structure for attributes (data) and methods (behaviour).

📖 Key Terms
Term Definition
Object An instance of a class with its own state and behaviour
Attribute A variable defined in a class (also called a class variable)
Instance Variable Attribute stored inside an individual object
Method A function defined within a class; describes object behaviour
Instantiation The process of creating an object from a class
Identifier The name used to refer to an object
CLASS: Student Attributes: name, dateOfBirth Methods: study(), attend() OBJECT: P1 name = "John" dateOfBirth = "06/10/2015" OBJECT: P2 name = "Sarah" dateOfBirth = "15/03/2014" instantiation instantiation

4.1 Prebuilt vs Custom Classes

Prebuilt Classes Custom Classes
Provided by the language Defined by the programmer
E.g., String, Date, Random, Scanner (Java) E.g., Animal, Student, Book

4.2 Programming a Class

Example Task: Define a class for a car sales program with attributes: Manufacturer, Model, Price, Mileage, PreOwned status. Create two car objects with appropriate identifiers.
Pseudocode - Car Class CLASS Cars // Private attributes PRIVATE Manufacturer : STRING PRIVATE Model : STRING PRIVATE Price : INTEGER PRIVATE Mileage : INTEGER PRIVATE PreOwned : BOOLEAN // Constructor PUBLIC PROCEDURE NEW(manufacturer, model, price, mileage, preOwned) SET Self.Manufacturer TO manufacturer SET Self.Model TO model SET Self.Price TO price SET Self.Mileage TO mileage SET Self.PreOwned TO preOwned ENDPROCEDURE // Methods PUBLIC PROCEDURE Accelerate() // Code to make the car go faster ENDPROCEDURE PUBLIC PROCEDURE HonkHorn() // Code to honk the car horn ENDPROCEDURE ENDCLASS
Python - Car Class class Cars: # Constructor def __init__(self, manufacturer, model, price, mileage, preOwned): self.__Manufacturer = manufacturer # Private attribute self.__Model = model self.__Price = price self.__Mileage = mileage self.__PreOwned = preOwned # Methods def Accelerate(self): # Code to make the car go faster pass def HonkHorn(self): # Code to honk the car horn pass

5. Objects (OOP)

An object is a representation of a real-world entity (e.g., teacher, aeroplane, mobile phone, cat). A class is like a blueprint that describes properties and behaviours, while an object is a specific instance with its own unique values.

📖 What is a Constructor?
CLASS Person - firstName - surname - dateOfBirth NEW CONSTRUCTOR Initialises attributes person1 "Bob", "Jones" "06/10/1981" person2 "Jess", "Jones" "05/04/1980"
Python - Creating Objects class Person: # Constructor - creates objects of the Person class def __init__(self, firstName, surname, dateOfBirth, hobbies): self.firstName = firstName self.surname = surname self.dateOfBirth = dateOfBirth self.hobbies = hobbies # Creating Objects (Instances) of the Person class person1 = Person("Bob", "Jones", "06/10/1981", "E Sports") person2 = Person("Jess", "Jones", "05/04/1980", "Astronomy")
Java - Creating Objects // Creating the Person class public class Person { // Creating 4 attributes for the Person class private String firstName; private String surname; private String dateOfBirth; private String hobbies; // Constructor - creates objects of the Person class public Person(String firstName, String surname, String dateOfBirth, String hobbies) { this.firstName = firstName; this.surname = surname; this.dateOfBirth = dateOfBirth; this.hobbies = hobbies; } } // Creating Objects (Instances) Person person1 = new Person("Bob", "Jones", "06/10/1981", "E Sports"); Person person2 = new Person("Jess", "Jones", "05/04/1980", "Astronomy");
🧠 Memory Trick: Class vs Object

Class = Blueprint (like an architectural drawing - defines structure)

Object = House (built from the blueprint - has actual values)

You can build many houses (objects) from one blueprint (class), each with different colours, furniture, etc. (attribute values).

6. Methods (OOP)

Methods are fundamental in OOP - they are functions associated with objects or classes that define the behaviour and actions that objects can perform.

6.1 Types of Methods

Type Description Example
Function Performs a task and returns a value CalculateTotal() returns a number
Procedure Performs a task but does NOT return a value DisplayMessage() just outputs text
CLASS Aircraft - manufacturer - model - passengerCapacity - speed TakeOff() Land() BankLeft() BankRight() jumboJet = Aircraft( "Boeing", "747") jumboJet.TakeOff() ← Object uses dot notation to call method

6.2 Instance vs Static Methods

📖 Instance Methods vs Static Methods

Instance Methods: Associated with individual instances (objects) of a class. They operate on the specific data and properties of an object.

Static Methods: Associated with a class itself and can be called without creating an instance (object) of the class.

6.3 Public vs Private Methods

Public Methods Private Methods
Accessible and can be invoked by any code within the same class or from any external classes Only accessible within the same class; cannot be invoked by external code or other classes
Changes may impact other parts of the codebase Changes have localized impact since used only internally
Used to provide access to functionalities or behaviours of an object Used for internal implementation details that should not be accessed externally
Pseudocode - Methods CLASS Aircraft // Attributes PRIVATE manufacturer : STRING PRIVATE model : STRING // Public method PUBLIC PROCEDURE TakeOff() OUTPUT "Aircraft taking off..." ENDPROCEDURE // Private method (internal use only) PRIVATE PROCEDURE CheckSystems() OUTPUT "Checking all systems..." ENDPROCEDURE ENDCLASS // Using the method jumboJet.TakeOff() // Valid - public method jumboJet.CheckSystems() // ERROR - private method not accessible
💡 Exam Tip

If a method does not specify the keyword public or private, the default is public. Always explicitly declare access modifiers for clarity in exams!

7. Attributes (OOP)

In OOP, an attribute refers to a data member or a property associated with an object or a class. They define the state of an object and can have different values for different instances of the same class.

📖 Key Points About Attributes
CLASS Car PRIVATE manufacturer - model : STRING - price : INTEGER - mileage : INTEGER - preOwned : BOOLEAN OBJECT: myCar manufacturer = "Ford" model = "Mustang" NEW

7.1 Programming Attributes

Pseudocode - Attributes CLASS Person // Attributes for the Person class PRIVATE name : STRING PRIVATE age : INTEGER PRIVATE gender : STRING PRIVATE occupation : STRING PRIVATE isMarried : BOOLEAN ENDCLASS
Python - Attributes class MyClass: def __init__(self, attribute1, attribute2): # Define attributes using self keyword self.attribute1 = attribute1 self.attribute2 = attribute2 # In Python, private attributes use double underscore prefix: class Person: def __init__(self, name, age): self.__name = name # Private attribute self.__age = age # Private attribute
⚠️ Important: Local Variables

Attributes declared within methods (local variables) cannot have access modifiers because they are local to the method and have limited scope. They are not part of the class's state and cannot be accessed from other methods or classes.

8. Inheritance (OOP)

Inheritance is a key concept in OOP that allows a class to inherit the properties and behaviours (methods and attributes) of another class. It promotes code reuse and establishes an "IS-A" relationship between classes.

📖 Key Inheritance Terms
Vehicle (Base Class) manufacturer, make, cost Car (Derived Class) + isInsured, engineCapacity Motorcycle (Derived Class) + hasSidecar Helicopter (Derived Class) + verticalPosition, maxHeight All derived classes inherit: turnEngineOn(), turnEngineOff(), steerLeft(), steerRight()

8.1 The super Keyword

The super keyword is used to refer to the superclass (base class) and access its members from within the subclass.

Python - Inheritance with super # Base class (Vehicle) class Vehicle: def __init__(self, manufacturer, make, cost): self.manufacturer = manufacturer self.make = make self.cost = cost def turn_engine_on(self): # Code to turn the engine on pass # Derived class (Car) - inherits from Vehicle class Car(Vehicle): # Parent class in parentheses def __init__(self, manufacturer, make, cost, is_insured, engine_capacity): # Use super to inherit attributes from base class super().__init__(manufacturer, make, cost) self.is_insured = is_insured self.engine_capacity = engine_capacity def gear_change(self): # Additional method for Car pass
Pseudocode - Inheritance CLASS Vehicle // Base class attributes PRIVATE manufacturer : STRING PRIVATE make : STRING PRIVATE cost : REAL // Constructor PUBLIC PROCEDURE NEW(manufacturer, make, cost) SET Self.manufacturer TO manufacturer SET Self.make TO make SET Self.cost TO cost ENDPROCEDURE ENDCLASS CLASS Car INHERITS Vehicle // Additional attributes for Car PRIVATE isInsured : BOOLEAN PRIVATE engineCapacity : REAL // Constructor PUBLIC PROCEDURE NEW(manufacturer, make, cost, isInsured, engineCapacity) CALL Super.NEW(manufacturer, make, cost) // Call parent constructor SET Self.isInsured TO isInsured SET Self.engineCapacity TO engineCapacity ENDPROCEDURE ENDCLASS
💡 Exam Tip

When writing inheritance code in exams, always show: (1) The INHERITS keyword in pseudocode, (2) Calling the parent constructor using super or equivalent, (3) Any additional attributes specific to the derived class.

9. Encapsulation (OOP)

Encapsulation refers to the practice of grouping data (attributes) and methods (functions) within a class. It ensures data remains secure by controlling access using access modifiers (public, private).

📖 Benefits of Encapsulation
CLASS (Encapsulation Boundary) PRIVATE - attributes - internal methods 🔒 Hidden PUBLIC + getters + setters 🔓 Accessible External Code ✓ via methods

9.1 Getters and Setters

📝 Get Methods (Accessors)
📝 Set Methods (Mutators)
Python - Getters and Setters class NumberUpdater: def __init__(self): self.__number = 10 # Private attribute # Getter method @property def number(self): return self.__number # Setter method with validation def set_number(self, new_number): if new_number < 0: # Keep old value if invalid self.__number = self.__number else: self.__number = new_number
Pseudocode - Getters FUNCTION GetCurrentSpeed() RETURNS INTEGER RETURN CurrentSpeed ENDFUNCTION FUNCTION GetIncreaseAmount() RETURNS INTEGER RETURN IncreaseAmount ENDFUNCTION FUNCTION GetHorizontalPosition() RETURNS INTEGER RETURN HorizontalPosition ENDFUNCTION
🧠 Memory Trick: Getters vs Setters

GET = Read (like "getting" information from a safe)

SET = Write (like "setting" a new value in a safe)

Both provide controlled access - the safe (encapsulation) protects the contents!

10. Polymorphism (OOP)

Polymorphism allows objects to take on different forms or behaviours. Different objects can share the same method name but work in different ways. It helps make code more flexible, reusable, and easier to maintain.

📖 Key Polymorphism Concepts
Animal speak() // empty (Base Class) Dog speak() → "Woof!" Overrides Cat speak() → "Meow!" Overrides make_sound(dog) → "Woof!" | make_sound(cat) → "Meow!"

10.1 Method Overriding Example

Pseudocode - Polymorphism CLASS Animal METHOD speak() // Empty method (placeholder) ENDMETHOD ENDCLASS CLASS Dog INHERITS Animal METHOD speak() OUTPUT "Woof" ENDMETHOD ENDCLASS CLASS Cat INHERITS Animal METHOD speak() OUTPUT "Meow" ENDMETHOD ENDCLASS PROCEDURE make_sound(animal : Animal) CALL animal.speak() // Calls correct method based on object type ENDPROCEDURE // Create objects DECLARE myDog : Dog DECLARE myCat : Cat SET myDog TO NEW Dog() SET myCat TO NEW Cat() // Demonstrate polymorphism CALL make_sound(myDog) // Outputs: Woof CALL make_sound(myCat) // Outputs: Meow
Python - Polymorphism class Animal: def speak(self): pass # Placeholder method class Dog(Animal): def speak(self): print("Woof") class Cat(Animal): def speak(self): print("Meow") def make_sound(animal): animal.speak() # Calls correct method at runtime dog = Dog() cat = Cat() make_sound(dog) # Outputs: Woof make_sound(cat) # Outputs: Meow
💡 Exam Tip

When explaining polymorphism in exams, mention that:

11. Declarative Programming

Declarative programming is a paradigm where you describe what you want the program to accomplish, not how to do it. SQL is a common example - you write queries to extract data without specifying control flow.

11.1 Components of Declarative Code

📖 Key Components
FACTS type(beagle, hound). size(labrador, large). shedding(poodle, low). ... RULES Logical relationships between facts IF-THEN logic QUERIES ?- size(X, large). X = labrador ; X = golden_retriever. Ask questions!

11.2 Prolog-Style Example: Dog Breeds

Prolog-Style Facts About Dog Breeds % Facts about dog types type(beagle, hound). type(labrador, retriever). type(poodle, companion). type(golden_retriever, retriever). type(bulldog, companion). % Facts about sizes size(beagle, medium). size(labrador, large). size(poodle, medium). size(golden_retriever, large). size(bulldog, medium). % Facts about shedding shedding(beagle, moderate). shedding(labrador, heavy). shedding(poodle, low). shedding(golden_retriever, heavy). shedding(bulldog, low).

11.3 Interpreting Clauses

Clause Meaning
type(poodle, companion). A poodle is a companion dog
size(labrador, large). A Labrador is a large-sized dog
shedding(bulldog, low). A bulldog has low shedding

11.4 Sample Queries

Prolog Queries % Is a poodle medium-sized? ?- size(poodle, medium). true. % What dogs are retrievers? ?- type(X, retriever). X = labrador ; X = golden_retriever. % Which dogs have low shedding AND are medium-sized? ?- shedding(X, low), size(X, medium). X = poodle ; X = bulldog.
💡 Exam Tip

In declarative programming, facts and rules can appear in any order. The interpreter matches patterns in queries against known facts. Remember: you describe the RESULT, not the PROCESS!

12. Exam-Style Questions

1. A computer game is being designed that includes different vehicles. Write program code to declare the class Vehicle. All attributes must be private. Each vehicle has: identification name, maximum speed, current speed, and horizontal position. [5 marks]

Marking Points:

  • Class header (and close where appropriate) [1 mark]
  • 5 (private) attribute declarations including data types [1 mark]
  • Constructor header taking minimum 3 parameters [1 mark]
  • Assigning ID, MaxSpeed and IncreaseAmount to parameters [1 mark]
  • Assigning CurrentSpeed and HorizontalPosition to 0 [1 mark]

Additional points for deeper understanding:

  • Python requires comment declarations for attribute types
  • Private attributes use double underscore prefix in Python
  • Java uses private keyword before each attribute
2. Explain the differences between imperative programming and declarative programming. Give an example language for each. [4 marks]

Answer:

  • Imperative: Tells the computer HOW to perform tasks using sequences of commands; explicit control flow with loops and conditions
  • Declarative: Describes WHAT should be done, not how; no explicit control flow; focuses on outcomes/results
  • Imperative example languages: Python, Java, C
  • Declarative example languages: SQL, Prolog, Haskell

Additional points:

  • Imperative uses step-by-step instructions; Declarative uses facts, rules, and queries
  • Imperative is better for general-purpose programming; Declarative excels at database queries and logic problems
3. Describe what is meant by encapsulation in object-oriented programming. Explain how encapsulation is achieved. [5 marks]

Answer:

  • Encapsulation is the practice of grouping data (attributes) and methods within a class
  • Ensures data remains secure by controlling access using access modifiers (public, private)
  • Private attributes can only be accessed within the class itself
  • Public methods (getters/setters) provide controlled access to private data
  • Hides implementation details through abstraction

Additional points:

  • Promotes code reusability and maintainability
  • External code interacts through public interface without knowing internal workings
4. The class Helicopter inherits from the parent class Vehicle. Write program code to declare the class Helicopter. A helicopter also has a vertical position and changes vertical position when it increases speed. All attributes must be private. [5 marks]

Marking Points:

  • Class header inheriting from Vehicle [1 mark]
  • 3 (private) attribute declarations with data types [1 mark]
  • Constructor with minimum 5 parameters [1 mark]
  • Calling parent constructor with appropriate parameters [1 mark]
  • Initialising VerticalPosition to 0 and VerticalChange, MaxHeight to attributes [1 mark]

Example code (Python):

class Helicopter(Vehicle): # VerticalPosition : INTEGER # VerticalChange : INTEGER # MaxHeight : INTEGER def __init__(self, IDP, MaxSpeedP, IncreaseAmountP, VertChangeP, MaxHeightP): Vehicle.__init__(self, IDP, MaxSpeedP, IncreaseAmountP) self.__VerticalPosition = 0 self.__VerticalChange = VertChangeP self.__MaxHeight = MaxHeightP
5. Explain the difference between a base class and a derived class in inheritance. Give an example. [4 marks]

Answer:

  • Base Class (Parent/Superclass): Serves as the blueprint/template; defines common properties and behaviours shared among derived classes
  • Derived Class (Child/Subclass): Inherits attributes and methods from the base class; can add additional attributes and methods
  • Establishes an "IS-A" relationship (e.g., Car IS-A Vehicle)
  • Example: Vehicle (base class) → Car (derived class); Car inherits manufacturer, make from Vehicle and adds engineCapacity

Additional points:

  • Derived classes can override parent methods
  • super keyword is used to access parent class members

12. Exam-Style Questions (Continued)

6. Write program code for the get methods: GetCurrentSpeed(), GetIncreaseAmount(), GetMaxSpeed(), and GetHorizontalPosition(). [3 marks]

Marking Points:

  • 1 get function header with no parameter [1 mark]
  • Returning attribute without overwriting [1 mark]
  • 3 further correct get methods [1 mark]

Example code (Python):

def GetCurrentSpeed(self): return self.__CurrentSpeed def GetIncreaseAmount(self): return self.__IncreaseAmount def GetHorizontalPosition(self): return self.__HorizontalPosition def GetMaxSpeed(self): return self.__MaxSpeed
7. Describe the five addressing modes used in low-level programming: immediate, direct, indirect, indexed, and relative. [5 marks]

Answer:

  • Immediate: Value is in the instruction itself (LOAD #5) - literal value
  • Direct: Instruction contains the memory address where data is stored (LOAD 100)
  • Indirect: Address points to another address where data is stored (LOAD @150)
  • Indexed: Effective address = base address + index register (LOAD 500[X]) - useful for arrays
  • Relative: Jump relative to current instruction position (BRANCH +3) - used for loops

Additional points:

  • Immediate is fastest but least flexible
  • Indexed is essential for array processing
8. Explain what is meant by polymorphism. Describe how method overriding demonstrates polymorphism. [5 marks]

Answer:

  • Polymorphism allows objects to take on different forms or behaviours
  • Different objects can share the same method name but work in different ways
  • Method overriding: Subclass provides a new implementation for a method defined in the parent class
  • The correct version is chosen at run-time, not compile-time
  • Example: Animal.speak() is overridden by Dog.speak() ("Woof") and Cat.speak() ("Meow")

Additional points:

  • Allows treating objects of different classes as objects of a common superclass
  • Enables flexible, maintainable code
9. Compare public and private methods in object-oriented programming. When would you use each? [4 marks]

Answer:

  • Public methods: Accessible from any code; used to provide external interface to object's functionality
  • Private methods: Only accessible within the same class; used for internal implementation details
  • Public methods allow controlled interaction with objects; changes may affect external code
  • Private methods provide encapsulation; changes have localized impact only

Additional points:

  • If no access modifier is specified, default is public
  • Private methods support the principle of information hiding
10. A Helicopter class has an IncreaseSpeed() method that overrides the parent Vehicle class method. The method adds vertical change to vertical position, limits to maximum height, and adds current speed to horizontal position. Write program code for this method. [4 marks]

Marking Points:

  • Method header (overriding where required) with no parameter [1 mark]
  • Adding vertical change to vertical position [1 mark]
  • Limiting to maximum height [1 mark]
  • Using code from original for horizontal increase [1 mark]

Example code (Python):

def IncreaseSpeed(self): self.__VerticalPosition = self.__VerticalPosition + self.__VerticalChange if self.__VerticalPosition > self.__MaxHeight: self.__VerticalPosition = self.__MaxHeight Vehicle.SetCurrentSpeed(self, Vehicle.GetCurrentSpeed(self) + Vehicle.GetIncreaseAmount(self)) if Vehicle.GetCurrentSpeed(self) > Vehicle.GetMaxSpeed(self): Vehicle.SetCurrentSpeed(self, Vehicle.GetMaxSpeed(self)) Vehicle.SetHorizontalPosition(self, Vehicle.GetHorizontalPosition(self) + Vehicle.GetCurrentSpeed(self))

13. Glossary

Abstraction - Hiding complex implementation details and showing only essential features to the user.
Access Modifier - Keywords (public, private) that control the visibility and accessibility of classes, methods, and attributes.
Attribute - A variable defined in a class that stores data; defines the state of an object.
Base Class - Also called parent or superclass; the class from which other classes inherit.
Class - A blueprint or template used to create objects; defines attributes and methods.
Constructor - A special method called automatically when an object is created; initialises the object's attributes.
Declarative Programming - A paradigm where you describe what you want, not how to achieve it.
Derived Class - Also called child or subclass; a class that inherits from a base class.
Encapsulation - Grouping data and methods within a class; controlling access through access modifiers.
Fact - In declarative programming, a statement that is known or assumed to be true.
Getter (Accessor) - A method that returns the value of a private attribute.
Imperative Programming - A paradigm where you tell the computer how to perform tasks step-by-step.
Inheritance - A mechanism where a class acquires properties and behaviours from another class.
Instance - A specific object created from a class.
Instantiation - The process of creating an object from a class.
Method - A function defined within a class that describes object behaviour.
Object - An instance of a class with its own state and behaviour.
Paradigm - A style or approach to programming that influences how programs are written and structured.
Polymorphism - The ability of objects to take different forms; same method name, different implementations.
Private - Access modifier that restricts access to within the same class only.
Procedural Programming - A type of imperative programming using procedures and functions.
Public - Access modifier that allows access from any code.
Query - In declarative programming, a question to retrieve information from a knowledge base.
Rule - In declarative programming, a logical relationship between facts.
Setter (Mutator) - A method that sets the value of a private attribute.
super - Keyword used to refer to the parent class from a derived class.

14. Exam Success Tips (Part 1)

💡 OOP Key Terms - Must Remember
💡 Access Modifiers - The Key Rule
💡 Inheritance - What to Include
🧠 Memory Trick: OOP Pillars

EIP = The three pillars of OOP:

💡 Addressing Modes Quick Reference

14. Exam Success Tips (Part 2)

❌ Common Mistakes to Avoid
💡 Answer Structure Tips
💡 Declarative Programming Tips
🌟 Quick Reference Table
Topic Key Point
Class Blueprint with attributes and methods
Object Instance of a class with actual values
Encapsulation Private attributes + public methods
Inheritance Child inherits from parent using super
Polymorphism Same method, different implementations
Getter Returns private attribute value
Setter Sets private attribute with validation

15. Key Takeaways

📌 Programming Paradigms
📌 Addressing Modes
📌 OOP Core Concepts
📌 Getters and Setters
📌 Final Exam Reminders