Question bank › IB Computer Science › B3 Object-oriented programming

OOP for multiple classes: inheritance, polymorphism, abstraction, composition, design patterns (HL)

Answer on paper first, then reveal the mark scheme one mark at a time.

1StandardHL only5 marks

Consider the program below.

class Vehicle:
    def __init__(self, reg, wheels=4):
        self.reg = reg
        self.wheels = wheels

    def describe(self):
        return self.reg + " has " + str(self.wheels) + " wheels"

class Motorbike(Vehicle):
    def __init__(self, reg):
        super().__init__(reg, 2)
        self.sidecar = False

    def describe(self):
        return super().describe() + " and no sidecar"

v = Vehicle("AB12")
m = Motorbike("XY99")
print(v.describe())
print(m.describe())
print(isinstance(m, Vehicle))

(a) State the output of the program. [3]

(b) Identify the method, other than the constructor __init__, that is overridden in Motorbike. [1]

(c) State the purpose of super().__init__(reg, 2). [1]

2StandardHL only4 marks

Consider the program below.

import math

class Shape:
    def area(self):
        return 0

class Circle(Shape):
    def __init__(self, r):
        self.r = r
    def area(self):
        return math.pi * self.r ** 2

class Rectangle(Shape):
    def __init__(self, w, h):
        self.w = w
        self.h = h
    def area(self):
        return self.w * self.h

for s in [Circle(3), Rectangle(4, 5)]:
    print(type(s).__name__ + ": " + format(s.area(), ".2f"))

(a) State the output. [2]

(b) Define the term polymorphism. [1]

(c) Outline how the for loop demonstrates polymorphism. [1]

3HardHL only6 marks

A library system uses the class diagram shown. Item is implemented as:

class Item:
    def __init__(self, title, item_id):
        self.title = title
        self.item_id = item_id

    def late_fee(self, days_late):
        return 0.10 * days_late

Book and DVD are subclasses of Item. A DVD costs £0.50 per day late; an ordinary Item costs £0.10 per day late.

(a) State the superclass and identify one attribute that a DVD object inherits. [2]

(b) Write the class DVD, including its constructor and a version of late_fee that charges £0.50 per day. [4]

Itemtitle, item_idlate_fee(days_late)BookauthorDVDdurationlate_fee(days_late)
Stuck on OOP for multiple classes: inheritance, polymorphism, abstraction, composition, design patterns (HL)?

Get it sorted in a free 30-minute session

We work through your weakest questions on this topic on Zoom. I reply the same day.

4StandardHL only6 marks

A bank's software is written in Java. The class Account is in the package bank:

package bank;

public class Account {
    private double balance;
    protected String owner;
    int branchCode;

    public String getOwner() {
        return owner;
    }
}

A programmer writes a subclass LoanAccount in a different package, loans:

package loans;
import bank.Account;

public class LoanAccount extends Account {
    void test() {
        owner = "Ana";        // Statement A
        balance = 0;          // Statement B
        branchCode = 12;      // Statement C
        getOwner();           // Statement D
    }
}

(a) For each of Statements A, B, C and D, state whether it compiles, giving the access modifier that decides this. [4]

(b) The programmer needs LoanAccount to reduce the balance when a repayment is taken. Without changing balance from private, outline how Account could be changed so that this is possible, and state one benefit of this approach. [2]

5CoreHL only5 marks

The UML class diagram shows part of a hotel booking system. Relationship P links Hotel and Room; relationship Q links Hotel and Guest.

(a) Identify the type of relationship shown by P and the type shown by Q. [2]

(b) With reference to rooms and guests, explain the difference between these two relationships when a Hotel object is deleted. [2]

(c) A student says that Room should be a subclass of Hotel. State why this is incorrect. [1]

Hotel name Room number Guest passportNo 1..* 0..* P Q
6StandardHL only7 marks

Consider the Java class below.

public class Printer {
    static String show(int x)        { return "int " + (x * 2); }
    static String show(double x)     { return "double " + (x / 2); }
    static String show(String s)     { return "String " + s.length(); }
    static String show(int x, int y) { return "two ints " + (x + y); }

    public static void main(String[] args) {
        System.out.println(show(7 / 2));
        System.out.println(show(7.0));
        System.out.println(show("seven"));
        System.out.println(show(3, 4));
    }
}

(a) State the output when main is run. [4]

(b) Explain why method overloading is described as static (compile-time) polymorphism. [2]

(c) A programmer adds the method static int show(int x) { return x; } to the class. State why the class will no longer compile. [1]

7HardHL only9 marks

A payroll program uses an abstract class.

from abc import ABC, abstractmethod

class Employee(ABC):
    def __init__(self, name):
        self.name = name

    @abstractmethod
    def monthly_pay(self):
        pass

    def payslip(self):
        return self.name + ": " + format(self.monthly_pay(), ".2f")

class Salaried(Employee):
    def __init__(self, name, salary):
        super().__init__(name)
        self.salary = salary

    def monthly_pay(self):
        return self.salary / 12

class Hourly(Employee):
    def __init__(self, name, hours, rate):
        super().__init__(name)
        self.hours = hours
        self.rate = rate

    def monthly_pay(self):
        return self.hours * self.rate

staff = [Salaried("Rao", 30000), Hourly("Kim", 82, 12.5)]
for e in staff:
    print(e.payslip())

(a) State the output of the program. [2]

(b) Explain why the statement Employee("Lee") would cause an error. [2]

(c) Explain how the abstract class Employee allows payslip to be written once for all types of employee. [2]

(d) A Contractor is paid a fixed rate for each day worked in the month. Construct the class Contractor, with a constructor taking name, days and day_rate. [3]

8StandardHL only7 marks

A program uses the singleton design pattern for a logger.

class Logger:
    _instance = None

    @staticmethod
    def get_instance():
        if Logger._instance is None:
            Logger._instance = Logger()
        return Logger._instance

    def __init__(self):
        self.lines = []

    def log(self, msg):
        self.lines.append(msg)
        return len(self.lines)

a = Logger.get_instance()
b = Logger.get_instance()
print(a.log("start"))
print(b.log("load"))
print(a is b)
print(len(a.lines))

(a) State the output of the program. [3]

(b) Explain the purpose of the singleton design pattern, with reference to this program. [2]

(c) Another programmer writes c = Logger(). Outline why this shows a weakness in this implementation of the pattern. [1]

(d) State one disadvantage of using the singleton pattern. [1]

9HardHL only8 marks

A program uses the observer design pattern.

class WeatherStation:
    def __init__(self):
        self.observers = []

    def attach(self, obs):
        self.observers.append(obs)

    def detach(self, obs):
        self.observers.remove(obs)

    def set_temp(self, t):
        for obs in self.observers:
            obs.update(t)

class Display:
    def __init__(self, name):
        self.name = name

    def update(self, t):
        print(self.name + " shows " + str(t))

class Alarm:
    def __init__(self, limit):
        self.limit = limit

    def update(self, t):
        if t > self.limit:
            print("ALARM " + str(t))

s = WeatherStation()
hall = Display("Hall")
lab = Display("Lab")
alarm = Alarm(30)
s.attach(hall)
s.attach(alarm)
s.set_temp(28)
s.attach(lab)
s.set_temp(31)
s.detach(hall)
s.set_temp(30)

(a) State the output of the program. [4]

(b) Identify the subject in this program. [1]

(c) Display and Alarm are unrelated classes. Explain how set_temp is still able to notify both. [1]

(d) A Logger class must also be notified of every new temperature. Explain one advantage of the observer pattern when adding this feature. [2]

10StretchHL only10 marks

A game contains the following classes.

class Enemy:
    def __init__(self, level):
        self.level = level
    def health(self):
        return 0

class Goblin(Enemy):
    def health(self):
        return 20 * self.level

class Troll(Enemy):
    def health(self):
        return 50 * self.level

class Dragon(Enemy):
    def health(self):
        return 200 + 40 * self.level

Enemies are created from text in a level file, such as "troll". The developers decide to use the factory design pattern.

(a) Construct a class EnemyFactory with a static method create(kind, level) that returns a Goblin, Troll or Dragon object of the given level for the strings "goblin", "troll" and "dragon", and raises a ValueError for any other string. [4]

(b) State the output of this code, which uses your factory. [1]

wave = ["goblin", "troll", "dragon", "goblin"]
total = 0
for k in wave:
    total = total + EnemyFactory.create(k, 3).health()
print(total)

(c) Explain one advantage of creating enemies through EnemyFactory rather than calling the constructors throughout the game code. [2]

(d) Some goblins, trolls and dragons must be able to fly. One developer proposes new subclasses FlyingGoblin, FlyingTroll and FlyingDragon. Another proposes that each Enemy holds a Movement object (for example Walk or Fly) and delegates movement to it. Evaluate the two proposals. [3]

Stuck on this topic?

Book a free 30-minute session on WhatsApp and we'll find exactly which step is costing you the marks. Or build a timed paper on it.

Free 30-minute session