Skip to the worksheet
Revision Library
Choose a subject

Object-Oriented Programming - Worksheets, Questions and Revision

8 original exam-style questions - 8 pages of questions with a full mark scheme - free printable PDF.

This topic is chapter 1 of A Level Computer Science Topic Workbook 2 and chapter 9 of A Level Computer Science 10-Minute Tests.

Revision Library
revisionlibrary.co.uk
A-Level · AQA

2.7 Object-Oriented Programming

AQA 7517 · Calculators not allowed · about 115 minutes
Total Marks
Name: _______________________________    Date: ____ / ____ / ______
Answer ALL questions. Show all your working.
1
A class diagram for a BankAccount class is shown below.

BankAccount
-----------------------------------
- accountNumber : String
- balance : Real
-----------------------------------
+ new(accNum : String, openingBalance : Real)
+ deposit(amount : Real) : Void
+ withdraw(amount : Real) : Boolean
+ getBalance() : Real
(a)State what the "-" symbol before accountNumber and balance indicates, and explain why a programmer would choose this visibility for these attributes.(3)
(b)Using AQA pseudocode conventions, write the class definition for BankAccount, including the constructor new(), the deposit() method, and the getBalance() method. The deposit() method should add amount to balance, provided amount is greater than 0.(6)
(c)Using AQA pseudocode conventions, write the withdraw(amount) method. It should return TRUE and reduce balance by amount if there are sufficient funds (balance ≥ amount); otherwise it should return FALSE and leave balance unchanged.(4)
(d)A second programmer suggests making balance a public attribute so that other parts of the program can update it directly, instead of using deposit() and withdraw(). Explain two problems this could cause.(3)
(Total for Question 1 is 16 marks)
2
A programmer is designing a class hierarchy to represent different shapes. The superclass Shape stores a colour attribute, and every shape (whatever its type) should have a method area() that calculates its own area.
(a)Using AQA pseudocode conventions, write the superclass Shape. It should have a private attribute colour, a constructor new(col) that sets colour, a method getColour() that returns colour, and a method area() that returns 0 (to be overridden by subclasses).(5)
(b)Write the subclass Circle, which inherits from Shape. It should have an additional private attribute radius, a constructor that accepts a colour and a radius (calling the superclass constructor to set the colour), and an overridden method area() that returns π * radius ^ 2.(6)
(c)Write the subclass Rectangle, which inherits from Shape. It should have additional private attributes width and height, a constructor that accepts a colour, width and height, and an overridden area() method that returns width * height.(4)
(d)Explain what is meant by "overriding" a method, using area() in Circle and Rectangle as your example.(2)
(Total for Question 2 is 17 marks)
3
A junior programmer has written the following class, but has not applied good object-oriented design principles.

class Student
public studentName
public examScore

public new(name, score)
     studentName <- name
     examScore <- score
  endnew
endclass

Elsewhere in the program, another part of the code contains the line:
student1.examScore <- 150
(a)Identify two problems with this class and the line of code shown above.(4)
(b)Rewrite the class using AQA pseudocode conventions so that studentName and examScore are properly encapsulated. Include a constructor, a getExamScore() method, and a setExamScore(newScore) method that only updates examScore if newScore is between 0 and 100 inclusive.(6)
(Total for Question 3 is 10 marks)
4
A library system uses a superclass Book with a private attribute title and a private attribute author. It has a constructor new(t, a) and a method getDetails() that returns a string in the form "title by author".

Two subclasses are needed:

EBook, which adds a private attribute fileSizeMB, with a constructor that also accepts the file size, and overrides getDetails() so it returns the Book version's string followed by " (ebook, " then the file size then "MB)".

PrintBook, which adds a private attribute shelfCode, with a constructor that also accepts the shelf code, and overrides getDetails() so it returns the Book version's string followed by " [Shelf: " then the shelf code then "]".
(a)Write the superclass Book, using AQA pseudocode conventions.(4)
(b)Write the subclass EBook.(5)
(c)Write the subclass PrintBook.(5)
(Total for Question 4 is 14 marks)
5
The following program creates an array of Book objects (using the classes from Question 4) and outputs the details of each one in turn.
library <- new Array(3)
library[0] <- new Book("Harbour Lights", "Amara Osei")
library[1] <- new EBook("The Long Tide", "Fatima Chowdhury", 4)
library[2] <- new PrintBook("Northbound", "Callum Ferguson", "F-12")

FOR i <- 0 TO 2
   OUTPUT library[i].getDetails()
ENDFOR
(a)Complete a trace table to show the exact string output on each pass of the loop.(6)
iOutput012
(b)Explain why it is good practice for EBook's getDetails() method to call super.getDetails() rather than rewriting the "title by author" logic again from scratch.(2)
(c)A fourth element, library[3], containing an Audiobook object (a further subclass of Book, not shown here, which also overrides getDetails()), is added, and the loop is changed to FOR i <- 0 TO 3. State which version of getDetails() would run for this new element, and explain why the existing loop code does not need to change to support it.(2)
(Total for Question 5 is 10 marks)
6
A start-up company is building a simulation of a hospital, modelling wards, patients, doctors and equipment, each with related data and behaviour, and expects to keep extending the simulation with new features for several years.

Discuss whether an object-oriented programming language or a procedural programming language would be more suitable for this project.
(Total for Question 6 is 9 marks)
7
The program below creates an array of three Shape objects (using the classes from Question 2) and processes them in a loop.
shapes <- new Array(3)
shapes[0] <- new Circle("red", 3)
shapes[1] <- new Rectangle("blue", 4, 5)
shapes[2] <- new Circle("green", 2)
total <- 0
FOR i <- 0 TO 2
   total <- total + shapes[i].area()
ENDFOR
OUTPUT total
(a)Complete a trace table to show the value returned by shapes[i].area() and the running value of total on each pass of the loop, and state the value finally output. Use π = 3.14159 and give values to 2 decimal places.(6)
(b)Explain why the line shapes[i].area() calls a different version of the area() method depending on whether shapes[i] refers to a Circle object or a Rectangle object. Use the term polymorphism in your answer.(3)
(c)Explain why the FOR loop uses FOR i <- 0 TO 2 rather than FOR i <- 0 TO 3, given that the array shapes holds three elements.(2)
(Total for Question 7 is 11 marks)
8
A company is developing a large payroll system. It currently has a single class, Employee, which includes attributes and methods for all types of staff, including office workers, managers and factory workers, with many IF statements inside its methods to handle the different types of employee differently.

A programmer suggests refactoring the system to use inheritance, creating subclasses such as Manager and FactoryWorker that inherit from Employee.

Discuss the extent to which using inheritance would improve the design of this payroll system.
(Total for Question 8 is 9 marks)
Mark scheme · 2.7 Object-Oriented Programming

Question 1

  • (a) "-" indicates the attribute is privateB1
  • (a) private attributes cannot be accessed or changed directly from outside the classB1
  • (a) this protects the data (encapsulation): balance can only be changed via methods such as deposit()/withdraw(), which can validate the change, e.g. preventing an invalid negative balance being set directly (oe)B1
  • (a) Answer: The "-" symbol means the attribute is private. This means accountNumber and balance cannot be accessed or altered directly from outside the class. This protects the data (encapsulation): balance, for example, can only be changed through methods such as deposit() and withdraw(), which can check that a change is valid before applying it, rather than any other part of the program being able to set an invalid value directly.
  • (b) class header class BankAccount with private accountNumber and private balance declaredM1
  • (b) constructor new(accNum, openingBalance) with both parameters correctly assigned to the attributesM1
  • (b) deposit(amount) method header definedM1
  • (b) IF amount > 0 THEN condition used to guard the updateM1
  • (b) balance <- balance + amount placed inside the IFM1
  • (b) getBalance() method that returns balance caoM1
  • (b) Answer:class BankAccount
    private accountNumber
    private balance

    public new(accNum, openingBalance)
         accountNumber <- accNum
         balance <- openingBalance
      endnew

    public deposit(amount)
         IF amount > 0 THEN
            balance <- balance + amount
         ENDIF
      enddeposit

    public getBalance()
         return balance
      endgetBalance
    endclass
  • (c) withdraw(amount) method header definedM1
  • (c) IF balance ≥ amount THEN condition usedM1
  • (c) balance <- balance - amount and return TRUE placed inside the IF branchM1
  • (c) ELSE branch returns FALSE, leaving balance unchanged caoM1
  • (c) Answer:public withdraw(amount)
       IF balance >= amount THEN
          balance <- balance - amount
          return TRUE
       ELSE
          return FALSE
       ENDIF
    endwithdraw
  • (d) problem 1: no validation would occur, so balance could be set directly to an invalid value, e.g. a negative number, with nothing checking itB1
  • (d) problem 2: it becomes harder to track down where/how balance changes in a large program, since any part of the code could alter it, not just deposit()/withdraw()B1
  • (d) further valid development, e.g. it breaks encapsulation, tightly coupling other code to BankAccount's internal representation, making future changes to the class harderB1
  • (d) Answer: Problem 1: without deposit()/withdraw() enforcing rules, balance could be set directly to an invalid value (e.g. a negative number) with no validation. Problem 2: it becomes much harder to find and debug where balance is changed, since any part of the program could alter it directly rather than only through the class's own methods; this breaks encapsulation and makes the class harder to maintain in future.

Question 2

  • (a) class header class Shape with private colour declaredM1
  • (a) constructor new(col) that assigns colour <- colM1
  • (a) getColour() method that returns colourM1
  • (a) area() method header definedM1
  • (a) return 0 inside area() caoM1
  • (a) Answer:class Shape
    private colour

    public new(col)
         colour <- col
      endnew

    public getColour()
         return colour
      endgetColour

    public area()
         return 0
      endarea
    endclass
  • (b) class Circle inherits Shape header with private radius declaredM1
  • (b) constructor new(col, rad) header definedM1
  • (b) super.new(col) used to call the superclass constructorM1
  • (b) radius <- rad assigned in the constructorM1
  • (b) area() method header overriding the superclass versionM1
  • (b) return π * radius ^ 2 caoM1
  • (b) Answer:class Circle inherits Shape
    private radius

    public new(col, rad)
    super.new(col)
         radius <- rad
      endnew

    public area()
         return pi * radius ^ 2
      endarea
    endclass
  • (c) class Rectangle inherits Shape header with private width and private height declaredM1
  • (c) constructor new(col, w, h) calling super.new(col) and assigning width <- w and height <- hM1
  • (c) area() method header overriding the superclass versionM1
  • (c) return width * height caoM1
  • (c) Answer:class Rectangle inherits Shape
    private width
    private height

    public new(col, w, h)
    super.new(col)
         width <- w
         height <- h
      endnew

    public area()
         return width * height
      endarea
    endclass
  • (d) overriding means a subclass provides its own implementation of a method already defined in its superclass, replacing the inherited version for objects of that subclassB1
  • (d) correct application: Circle and Rectangle both define their own area() with different logic to Shape's area() (which returns 0), so calling area() on a Circle object runs Circle's version, not Shape'sB1
  • (d) Answer: Overriding means a subclass defines its own version of a method that already exists in its superclass, and this version is used instead of the superclass's version for objects of that subclass. Here, Circle and Rectangle each provide their own area() method, with different formulas to the area() in Shape (which just returns 0), so calling area() on a Circle object executes Circle's own area() method.

Question 3

  • (a) problem 1 identified: both attributes are public, so they can be accessed and changed directly from anywhere in the program, breaking encapsulationB1
  • (a) problem 1 developed: this allows the line student1.examScore <- 150 to set examScore directly with no check at allB1
  • (a) problem 2 identified: the class has no validation logic (e.g. no setter method) to enforce rules on new valuesB1
  • (a) problem 2 developed: so an invalid score, such as 150 (presumably above a maximum possible mark of 100), can be stored without being rejectedB1
  • (a) Answer: Problem 1: studentName and examScore are declared public, so any part of the program can access or change them directly, breaking encapsulation - this is why the line student1.examScore <- 150 is allowed to run at all. Problem 2: the class has no method that validates a new exam score before storing it, so an invalid value such as 150 (assuming scores should be 0 to 100) is accepted with no check.
  • (b) private studentName and private examScore declaredM1
  • (b) constructor new(name, score) correctly assigning both parameters to the attributesM1
  • (b) getExamScore() method that returns examScoreM1
  • (b) setExamScore(newScore) method header definedM1
  • (b) IF newScore ≥ 0 AND newScore ≤ 100 THEN condition used (oe, e.g. two nested IFs)M1
  • (b) examScore <- newScore placed inside the IF, so an out-of-range value is simply not stored caoM1
  • (b) Answer:class Student
    private studentName
    private examScore

    public new(name, score)
         studentName <- name
         examScore <- score
      endnew

    public getExamScore()
         return examScore
      endgetExamScore

    public setExamScore(newScore)
         IF newScore >= 0 AND newScore <= 100 THEN
            examScore <- newScore
         ENDIF
      endsetExamScore
    endclass

Question 4

  • (a) class header class Book with private title and private author declaredM1
  • (a) constructor new(t, a) correctly assigning both parameters to the attributesM1
  • (a) getDetails() method header definedM1
  • (a) return title + " by " + author (or equivalent using the stored attributes) caoM1
  • (a) Answer:class Book
    private title
    private author

    public new(t, a)
         title <- t
         author <- a
      endnew

    public getDetails()
         return title + " by " + author
      endgetDetails
    endclass
  • (b) class EBook inherits Book header with private fileSizeMB declaredM1
  • (b) constructor new(t, a, size) header definedM1
  • (b) super.new(t, a) used to call the superclass constructor, and fileSizeMB <- size assignedM1
  • (b) getDetails() overridden and calls super.getDetails() to reuse the Book formatM1
  • (b) return details + " (ebook, " + fileSizeMB + "MB)" caoM1
  • (b) Answer:class EBook inherits Book
    private fileSizeMB

    public new(t, a, size)
    super.new(t, a)
         fileSizeMB <- size
      endnew

    public getDetails()
         details <- super.getDetails()
         return details + " (ebook, " + fileSizeMB + "MB)"
      endgetDetails
    endclass
  • (c) class PrintBook inherits Book header with private shelfCode declaredM1
  • (c) constructor new(t, a, code) header definedM1
  • (c) super.new(t, a) used to call the superclass constructor, and shelfCode <- code assignedM1
  • (c) getDetails() overridden and calls super.getDetails() to reuse the Book formatM1
  • (c) return details + " [Shelf: " + shelfCode + "]" caoM1
  • (c) Answer:class PrintBook inherits Book
    private shelfCode

    public new(t, a, code)
    super.new(t, a)
         shelfCode <- code
      endnew

    public getDetails()
         details <- super.getDetails()
         return details + " [Shelf: " + shelfCode + "]"
      endgetDetails
    endclass

Question 5

  • (a) i = 0 output: Harbour Lights by Amara OseiB1
  • (a) i = 1 base part correct: The Long Tide by Fatima ChowdhuryB1
  • (a) i = 1 suffix correct: (ebook, 4MB)B1
  • (a) i = 2 base part correct: Northbound by Callum FergusonB1
  • (a) i = 2 suffix correct: [Shelf: F-12]B1
  • (a) all three outputs given in the correct loop order caoB1
  • (a) Answer:i=0 output: Harbour Lights by Amara Osei
    i=1 output: The Long Tide by Fatima Chowdhury (ebook, 4MB)
    i=2 output: Northbound by Callum Ferguson [Shelf: F-12]
  • (b) avoids duplicating code that already exists in the superclass Book, so if the format of getDetails() in Book ever changes, it only needs to be updated in one placeB1
  • (b) reduces the risk of errors/inconsistency between subclasses (e.g. EBook producing the base string in a slightly different way to Book or to PrintBook)B1
  • (b) Answer: Calling super.getDetails() reuses the logic already written in Book, so the "title by author" format only needs to be written and maintained in one place. This also avoids the risk of EBook (or PrintBook) accidentally producing a slightly different or inconsistent base string if the logic were rewritten separately in each subclass.
  • (c) Audiobook's own overridden version of getDetails() would run, not Book's, because of polymorphism/dynamic method dispatch: an object always uses its own class's version of an overridden methodB1
  • (c) the loop code library[i].getDetails() does not need to know which specific subclass each element is, so it works for Audiobook without any changeB1
  • (c) Answer: Audiobook's own overridden getDetails() method would run, not Book's, because of polymorphism - each object always uses its own class's version of an overridden method. The existing loop simply calls library[i].getDetails() for whatever object is stored at that index, so it automatically works correctly for the new Audiobook subclass without any modification.

Question 6

  • Level 3 A clear, well-supported discussion applies features of OOP (classes/objects modelling real-world entities; encapsulation protecting data; inheritance/polymorphism supporting shared and specialised behaviour) directly to the hospital scenario, compares this with procedural characteristics, and reaches a justified conclusion while acknowledging at least one valid counterpoint.7-9
  • Level 2 Some accurate comparison of OOP and procedural approaches is given with partial application to the hospital scenario, but development is limited, the discussion is one-sided (no real counterpoint), or there is some inaccuracy.4-6
  • Level 1 Generic, undeveloped statements about OOP and/or procedural programming are made with little or no reference to the given scenario.1-3
  • Level 0 No creditable content.0
  • Indicative content:
    • The hospital simulation involves distinct real-world entities (Patient, Doctor, Ward, Equipment), each with its own data and behaviour, which map naturally onto classes and objects in OOP.
    • Encapsulation would let each class protect its own data, e.g. a Patient's medical data could only be changed through the Patient class's own methods, reducing the risk of other parts of the simulation corrupting it.
    • Inheritance could model variations, e.g. different types of Ward (GeneralWard, IntensiveCareWard) inheriting shared attributes/methods from a Ward superclass while overriding specific behaviour.
    • Polymorphism would let code that processes a collection of, for example, different types of Staff call the same method name and automatically get the correct behaviour for each specific subclass.
    • Since the company plans to keep extending the simulation for years, OOP's support for adding new subclasses without editing existing, tested code is well suited to a long-lived, growing project.
    • Procedural programming (writing the program as a series of procedures/functions operating on shared data) can be simpler and quicker for small, short-lived programs, but keeping track of which procedures affect which data can become harder to manage as more features and data types are added.
    • Counterpoint: OOP can introduce more upfront design effort, and in some cases performance overhead, compared with an equivalent procedural program; this may not be justified for a very small or short-lived project, but the scenario described (a large, long-running simulation) does not fit that case.

Question 7

  • (a) i = 0: shapes[0].area() = 28.27 (Circle radius 3: π * 32)B1
  • (a) i = 1: shapes[1].area() = 20.00 (Rectangle 4 * 5)B1
  • (a) i = 2: shapes[2].area() = 12.57 (Circle radius 2: π * 22)B1
  • (a) total after i = 0 is 28.27B1
  • (a) total after i = 1 is 48.27B1
  • (a) total (and final output) after i = 2 is 60.84 caoB1
  • (a) Answer:
    ishapes[i].area()total
    028.2728.27
    120.0048.27
    212.5760.84

    Output: 60.84
  • (b) this is an example of polymorphism: objects of different classes (Circle, Rectangle) can be treated as objects of a common superclass (Shape) and stored together, e.g. in the same arrayB1
  • (b) although the same method name area() is called each time, at run-time the actual object's own (overridden) version of area() executes rather than Shape's version - this is sometimes called dynamic/late bindingB1
  • (b) this means the same line of code shapes[i].area() works correctly for every subclass, without the programmer needing to write separate code to check the type of each shapeB1
  • (b) Answer: This is an example of polymorphism. Circle and Rectangle are both subclasses of Shape, so their objects can be stored together in the same shapes array and processed with the same code. Even though every call looks identical (shapes[i].area()), at run-time each object runs its own overridden version of area() (Circle's or Rectangle's), not the version in Shape. This means the loop does not need any extra code to check what type of shape each element is.
  • (c) array indices in this pseudocode start at 0 (zero-indexed), so the three elements are stored at indices 0, 1 and 2B1
  • (c) using TO 3 would attempt to access shapes[3], which does not exist, causing a run-time (out-of-bounds/invalid index) errorB1
  • (c) Answer: The array is zero-indexed, so its three elements are at indices 0, 1 and 2 - there is no index 3. If the loop used FOR i <- 0 TO 3, it would try to access shapes[3], which does not exist, causing a run-time error.

Question 8

  • Level 3 A well-argued discussion identifies several clear benefits of using inheritance in this specific scenario (e.g. removing repeated IF statements, allowing subclasses to override/extend shared behaviour, easing the addition of future employee types), and also considers at least one limitation or counterpoint (e.g. added design complexity, the risk of a poorly-planned hierarchy, or the cost/risk of refactoring existing code), reaching a supported conclusion.7-9
  • Level 2 Some relevant benefits of using inheritance are identified with partial application to the payroll scenario, but discussion of limitations or counterpoints is limited or missing, or the explanation lacks depth or scenario-specific detail.4-6
  • Level 1 Basic, largely generic statements about inheritance are made with little or no application to the payroll scenario described.1-3
  • Level 0 No creditable content.0
  • Indicative content:
    • Attributes/methods common to all staff (e.g. name, employee number, a method to calculate basic pay) would only need to be written once, in the Employee superclass.
    • Manager and FactoryWorker subclasses would inherit these automatically, then add their own extra attributes/methods (e.g. Manager might add a teamSize attribute and a calculateBonus() method).
    • Subclasses could override a method such as calculatePay(), replacing the current IF statements that check employee type, so each subclass's own logic is self-contained and easier to follow and maintain.
    • Adding a new type of employee in future (e.g. Apprentice) would mean creating a new subclass, without needing to edit and re-test the existing Employee class or its other subclasses.
    • Counterpoint: designing a good class hierarchy takes upfront planning; if roles do not fit neatly into an is-a hierarchy (e.g. an employee who is both a manager and a factory worker), inheritance alone may not model the situation well.
    • Counterpoint: refactoring existing, working code carries risk and cost, and the benefits are most worthwhile if the system will genuinely be extended and maintained over a long period, which the scenario suggests is the case here.

Mark your answers

Check answers without an account. Some answers can be checked automatically; use the mark scheme to mark the rest.

Question 1

16 marks
Did your answer earn the marks?

Question 2

17 marks
Did your answer earn the marks?

Question 3

10 marks
Did your answer earn the marks?

Question 4

14 marks
Did your answer earn the marks?

Question 5

10 marks
Did your answer earn the marks?

Question 6

9 marks
Did your answer earn the marks?

Question 7

11 marks
Did your answer earn the marks?

Question 8

9 marks
Did your answer earn the marks?
Mark my answers

Worksheets are written for Revision Library and come with a full mark scheme; a few English packs quote an out-of-copyright text, and name it on the page. Exam board names and specification codes say which qualification a pack suits: we are not affiliated with, endorsed by or approved by any exam board, and no past-paper question is reproduced here. Rights queries: hello@revisionlibrary.co.uk