Object-Oriented Programming - Worksheets, Questions and Revision
8 original exam-style questions - 8 pages of questions with a full mark scheme - free printable PDF.
Object-Oriented Programming revision guideMore A Level Computer Science practiceMock exams
This topic is chapter 1 of A Level Computer Science Topic Workbook 2 and chapter 9 of A Level Computer Science 10-Minute Tests.
2.7 Object-Oriented Programming
BankAccount
-----------------------------------
- accountNumber : String
- balance : Real
-----------------------------------
+ new(accNum : String, openingBalance : Real)
+ deposit(amount : Real) : Void
+ withdraw(amount : Real) : Boolean
+ getBalance() : Real
class Student
public studentName
public examScore
public new(name, score)
studentName <- name
examScore <- score
endnewElsewhere in the program, another part of the code contains the line:
student1.examScore <- 150
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 "]".
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()Discuss whether an object-oriented programming language or a procedural programming language would be more suitable for this project.
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()OUTPUT total
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.
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 ENDIFendwithdraw - (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 endsetExamScoreendclass
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)" endgetDetailsendclass - (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 + "]" endgetDetailsendclass
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:
i shapes[i].area() total 0 28.27 28.27 1 20.00 48.27 2 12.57 60.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.