IB DP · Thinka-original Practice Paper

2023 IB DP Computer Science Practice Paper with Answers

Thinka May 2023 SL (TZ2) IB Diploma Programme-Style Mock — Computer Science

115 marks150 mins2023
An original Thinka practice paper modelled on the structure and difficulty of the May 2023 SL (TZ2) IB Diploma Programme Computer Science paper. Not affiliated with or reproduced from IB.

Paper 1 Section A

Answer all questions in the space provided.
9 Question · 25.020000000000003 marks
Question 1 · Short Answer
2.78 marks
A hospital is planning to update its electronic health record (EHR) system. Outline one disadvantage of using a direct changeover method compared to a parallel running method for this transition.
Show answer & marking scheme

Worked solution

In a direct changeover, the old system is immediately decommissioned and the new system is fully implemented. If the new system contains major undetected bugs or fails entirely, there is no alternative system operational to fall back on, which can lead to catastrophic operational disruption in a hospital environment.

Marking scheme

Award up to 2.78 marks: 1.39 marks for identifying the high risk or lack of a fallback system, and 1.39 marks for explaining the potential consequences in the context of the hospital environment.
Question 2 · Short Answer
2.78 marks
Describe the role of the Memory Address Register (MAR) during the fetch stage of the machine instruction cycle.
Show answer & marking scheme

Worked solution

During the fetch stage, the CPU copies the address stored in the Program Counter (PC) to the Memory Address Register (MAR). The MAR then places this address on the address bus so that the physical RAM location can be addressed and the instruction retrieved.

Marking scheme

Award up to 2.78 marks: 1.39 marks for identifying that MAR receives the instruction address from the Program Counter, and 1.39 marks for describing how it uses the address bus to locate the instruction in RAM.
Question 3 · Short Answer
2.78 marks
Explain how a Virtual Private Network (VPN) provides secure communication for a remote employee accessing a company's private server over the internet.
Show answer & marking scheme

Worked solution

A VPN secures the connection by encrypting all data packets before they travel over the public internet, ensuring that interceptors cannot read the content. It also creates a secure, authenticated tunnel between the remote client and the corporate network, hiding the user's actual external IP address.

Marking scheme

Award up to 2.78 marks: 1.39 marks for explaining how data encryption ensures confidentiality, and 1.39 marks for describing how tunneling or secure authentication prevents interception.
Question 4 · Short Answer
2.78 marks
An integer array NUMS is defined as [12, 5, 8, 3, 14]. A standard bubble sort algorithm is applied to sort the array in ascending order. State the state of the array NUMS after the completion of the first full pass.
Show answer & marking scheme

Worked solution

Tracing the first pass of bubble sort on [12, 5, 8, 3, 14]: 1. Compare 12 and 5: swap to [5, 12, 8, 3, 14]. 2. Compare 12 and 8: swap to [5, 8, 12, 3, 14]. 3. Compare 12 and 3: swap to [5, 8, 3, 12, 14]. 4. Compare 12 and 14: no swap [5, 8, 3, 12, 14]. At the end of the pass, the largest value (14) has settled at the final position.

Marking scheme

Award 2.78 marks for the exact correct final array [5, 8, 3, 12, 14]. Award 1.39 marks if one element is misplaced but the bubbles-to-the-end trace is partially correct.
Question 5 · Short Answer
2.78 marks
Identify two accessibility features that can be implemented in a mobile operating system to improve usability for visually impaired users.
Show answer & marking scheme

Worked solution

Visual accessibility features include screen readers (which read interface elements aloud using text-to-speech feedback) and visual adjustment mechanisms such as screen magnifiers, scalable large-text options, or high-contrast color themes.

Marking scheme

Award 1.39 marks for each correct accessibility feature identified, up to a maximum of 2.78 marks (e.g., screen readers, magnification tools, high contrast modes, voice assistants).
Question 6 · Short Answer
2.78 marks
Distinguish between Random Access Memory (RAM) and Read-Only Memory (ROM) in terms of volatility and writeability.
Show answer & marking scheme

Worked solution

RAM is volatile, meaning it loses all stored data when power is lost, and it allows dynamic reading and writing. ROM is non-volatile, preserving stored data even without power, and is permanently written during manufacture, making it read-only during normal runtime operations.

Marking scheme

Award up to 2.78 marks: 1.39 marks for correctly distinguishing their volatility, and 1.39 marks for correctly distinguishing their write/read capabilities.
Question 7 · Short Answer
2.78 marks
State two items of metadata typically found in the header of a data packet sent over a packet-switched network.
Show answer & marking scheme

Worked solution

The header of a network packet contains crucial metadata for routing and assembly, which includes the sender's (source) IP address, the receiver's (destination) IP address, the sequence number of the packet, and error-checking checksums.

Marking scheme

Award 1.39 marks for each correct item identified, up to a maximum of 2.78 marks (e.g., source IP, destination IP, packet sequence number, checksum).
Question 8 · Short Answer
2.78 marks
Consider the following recursive algorithm: function mystery(n) if n <= 1 then return 1 else return n * mystery(n - 1) end if end function. Calculate the return value of the function call mystery(4).
Show answer & marking scheme

Worked solution

Evaluating mystery(4): it returns 4 * mystery(3). mystery(3) returns 3 * mystery(2). mystery(2) returns 2 * mystery(1). mystery(1) reaches the base case and returns 1. Computing back upwards: mystery(2) = 2 * 1 = 2; mystery(3) = 3 * 2 = 6; mystery(4) = 4 * 6 = 24.

Marking scheme

Award 2.78 marks for the correct integer value 24. Award 1.39 marks if the mathematical expansion was correctly worked out but a minor arithmetic mistake occurred.
Question 9 · Short Answer
2.78 marks
Describe the roles of the Memory Address Register (MAR) and the Memory Data Register (MDR) during the fetch stage of the machine instruction cycle.
Show answer & marking scheme

Worked solution

1. The Program Counter (PC) holds the address of the next instruction, which is copied to the Memory Address Register (MAR). 2. The MAR uses the address bus to locate the instruction in RAM. 3. The instruction at that address is copied via the data bus into the Memory Data Register (MDR).

Marking scheme

Award up to 2.78 marks as follows: 1 mark for stating that the MAR receives or holds the address of the next instruction to be fetched (from the PC); 1 mark for explaining that the MAR points to or accesses the specific address in RAM; 0.78 marks for explaining that the instruction or data located at that memory address is loaded into the MDR.

Paper 1 Section B

Answer all questions. Each scenario represents 15 marks.
3 Question · 45 marks
Question 1 · Structured Scenario
15 marks
A localized medical clinic is upgrading its old paper-based medical files to a modern, cloud-based Electronic Health Record (EHR) system. The new system will allow doctors to access patient histories on mobile tablets during consultations.

(a) Outline two social or ethical issues associated with this system upgrade. [4 marks]

(b) Describe how the clinic could use a parallel changeover method to transition to the new EHR system, and state one advantage and one disadvantage of this choice. [4 marks]

(c) Explain the role of a prototype during the design stage of this EHR system. [3 marks]

(d) Suggest two distinct methods to prevent unauthorized data access to patient records when they are transmitted to the cloud. [4 marks]
Show answer & marking scheme

Worked solution

(a)
- Issue 1: Privacy and Confidentiality. Unauthorized individuals might intercept patient records during transmission or access them due to weak authentication mechanisms, exposing highly private health data.
- Issue 2: Digital Divide / Staff Training. Some medical staff or patients may lack the necessary IT literacy, resulting in errors in data entry or frustration during the transition phase, which could temporarily impact patient care.

(b)
- Implementation: Both the legacy paper-based system and the new cloud-based EHR system run concurrently. Doctors enter patient records into both systems for a specified period (e.g., one month) until the new system is verified to work correctly.
- Advantage: Low risk; if the new EHR system suffers a failure or data loss, the clinic has the paper files as an active and up-to-date backup.
- Disadvantage: High workload and duplication of effort; staff must perform double data entry, which can lead to stress and reduced time for patient care.

(c)
- A prototype provides an early, simplified version of the user interface and basic system workflow.
- It allows doctors and clinic staff to test the usability of the software on mobile tablets and provide feedback to developers early in the process.
- This helps identify design flaws, clarify system requirements, and prevent expensive revisions after the software is fully developed.

(d)
- Method 1: Data Encryption (e.g., utilizing HTTPS/TLS protocols) during transmission. This scrambles the patient records into unreadable ciphertext so that even if intercepted, they cannot be read without the private decryption key.
- Method 2: Virtual Private Network (VPN). Establishes an encrypted network tunnel specifically between the clinic's local network/devices and the cloud servers, ensuring data is shielded from public internet inspection.

Marking scheme

(a) [4 marks]
- 1 mark for identifying a valid social/ethical issue.
- 1 mark for outlining it in the context of the clinic up to 2 issues.
(Accept: Privacy/security leaks, digital exclusion, data loss during migration, consent of patient records transfer).

(b) [4 marks]
- 2 marks for describing parallel implementation correctly in this context (running both concurrently, double entry).
- 1 mark for a valid advantage (failsafe/redundancy/low risk).
- 1 mark for a valid disadvantage (increased workload/inefficient).

(c) [3 marks]
- 1 mark for defining/describing a prototype (early interactive mock-up).
- 1 mark for explaining stakeholder feedback (interaction with doctors/nurses).
- 1 mark for connecting this to system improvement (clarifying requirements, reducing final costs, error reduction).

(d) [4 marks]
- 1 mark for identifying a security method.
- 1 mark for explaining how it prevents unauthorized access, up to 2 methods.
(Award max 2 marks for simple lists without explanation. Acceptable methods: End-to-end encryption, VPN, Multi-factor authentication for transit endpoints, secure API gateways).
Question 2 · Structured Scenario
15 marks
A smart school uses an array of Internet of Things (IoT) devices, including automated attendance registers, smart classroom lighting, and security cameras. All these devices connect wirelessly to a central school server.

(a) Define the term protocol in the context of network communications. [2 marks]

(b) Explain why a wireless network (WLAN) is more suitable than a wired network (LAN) for the school's smart devices, and discuss one security drawback of this choice. [4 marks]

(c) Describe the function of a router in directing data packets from an IoT device to the school's internal server. [3 marks]

(d) Explain how data encryption and MAC address filtering can be used together to secure the school's wireless network. [6 marks]
Show answer & marking scheme

Worked solution

(a)
- A protocol is a set of standardized rules and guidelines that govern how data is formatted, transmitted, and received across a network, ensuring that different devices can communicate successfully.

(b)
- Suitability: High flexibility and lower installation costs. Smart devices can be placed anywhere in the school building (e.g., ceilings, outdoor walls) without laying down expensive physical ethernet cabling. It is also highly scalable, allowing new IoT devices to be added seamlessly.
- Security Drawback: Physical boundaries do not contain wireless signals. Unauthorized users outside the school premises can intercept wireless signals (eavesdropping) or attempt to access the network remotely.

(c)
- The router receives data packets from the IoT devices over the local wireless access point.
- It inspects the destination IP address contained in the packet headers.
- It references its routing table to determine the most efficient path through the network and forwards the packet to the next hop or directly to the school's internal server.

(d)
- Data Encryption: Converts the plain text data sent by IoT devices into ciphertext using an encryption algorithm and key. Even if an attacker intercepts the wireless signal, the intercepted data remains unreadable without the correct decryption key.
- MAC Address Filtering: The wireless access point maintains an access control list of approved Media Access Control (MAC) addresses (the physical, unique identifiers of the school's IoT hardware). Any device attempting to connect whose MAC address is not on this whitelist will be blocked immediately from joining the network.
- Synthesis: Combined, MAC filtering prevents unauthorized devices from establishing physical/logical connections, while encryption protects data confidentiality in case authorized channels are sniffed or bypassed.

Marking scheme

(a) [2 marks]
- 1 mark for defining protocol as a set of rules/standards.
- 1 mark for explaining its purpose (enabling successful, understandable communication/data exchange between devices).

(b) [4 marks]
- 2 marks for explaining suitability (mobility, ease of deployment, scalability, absence of physical cabling in tight locations).
- 2 marks for discussing the security drawback (signal leakage beyond school walls, vulnerability to sniffing or man-in-the-middle attacks).

(c) [3 marks]
- 1 mark for receiving packets and reading destination IP addresses in headers.
- 1 mark for mentioning the use of a routing table/routing protocols.
- 1 mark for forwarding the packet along the optimal/fastest path towards the school server.

(d) [6 marks]
- Up to 3 marks for describing data encryption (mentioning plaintext/ciphertext, key requirement, and protection of confidentiality during transit).
- Up to 3 marks for describing MAC address filtering (mentioning physical/unique hardware addresses, whitelisting, and blocking unauthorized access at the connection phase).
Question 3 · Structured Scenario
15 marks
An online delivery company operates a fleet of autonomous delivery robots. An algorithm is needed to manage a list of packages and assign them to robots based on their delivery weight capacity.

(a) Describe how a queue structure differs from a stack structure, and explain why a queue is suitable for processing incoming delivery orders. [4 marks]

(b) Construct pseudocode for an algorithm that takes an array of 5 packages (where each package has a property .weight) and separates them into two distinct queues: HEAVY_QUEUE (for weights greater than 10kg) and LIGHT_QUEUE (for weights 10kg or less). Assume the queues HEAVY_QUEUE and LIGHT_QUEUE are already defined and have an .enqueue() method. [5 marks]

(c) Explain the role of a trace table during the testing of this algorithm. [3 marks]

(d) Discuss the necessity of standard algorithms, such as sorting algorithms, in managing large-scale package sorting operations. [3 marks]
Show answer & marking scheme

Worked solution

(a)
- Difference: A queue is a First-In-First-Out (FIFO) data structure where elements are added at the rear and removed from the front. In contrast, a stack is a Last-In-First-Out (LIFO) structure where elements are added and removed from the same end (the top).
- Suitability: A queue is suitable for incoming delivery orders because it preserves chronological fairness, ensuring that the first customer who places an order is the first customer whose package is processed and delivered.

(b)
```
// Assuming PACKAGES is an array containing 5 package objects
loop I from 0 to 4
CURRENT_PACKAGE = PACKAGES[I]
if CURRENT_PACKAGE.weight > 10 then
HEAVY_QUEUE.enqueue(CURRENT_PACKAGE)
else
LIGHT_QUEUE.enqueue(CURRENT_PACKAGE)
end if
end loop
```

(c)
- A trace table is used to manually dry-run the algorithm step-by-step.
- It records the values of variables (like index `I`, `CURRENT_PACKAGE.weight`, and queue states) at each line of execution.
- This allows developers to check for logical errors, off-by-one errors in the loop limits, or incorrect branching decisions without needing to compile or run the code.

(d)
- Standard algorithms (like Quick Sort or Merge Sort) are highly optimized and have known time complexities (such as \(O(N \log N)\)).
- Using them ensures the system remains scalable when handling hundreds of thousands of packages, preventing system lag.
- They are pre-tested and reliable, which reduces development time and prevents software bugs in high-throughput enterprise environments.

Marking scheme

(a) [4 marks]
- 2 marks for contrasting FIFO (queue) and LIFO (stack) operations.
- 2 marks for justifying the queue (fairness, processing in order of arrival, preventing older orders from starvation).

(b) [5 marks]
- 1 mark for establishing a loop that executes exactly 5 times (0 to 4).
- 1 mark for accessing the element from the array using the loop index.
- 1 mark for the correct conditional statement check (weight > 10).
- 1 mark for correctly calling HEAVY_QUEUE.enqueue() and LIGHT_QUEUE.enqueue() in the appropriate branches.
- 1 mark for correct logical nesting and block termination (end if, end loop/next).

(c) [3 marks]
- 1 mark for stating it tracks the changes in variable values during execution.
- 1 mark for explaining that it traces execution step-by-step/line-by-line.
- 1 mark for identifying its output as finding dry-run logical/boundary errors.

(d) [3 marks]
- 1 mark for discussing efficiency/computational complexity (e.g., \(O(N \log N)\) vs \(O(N^2)\)).
- 1 mark for discussing scalability in large systems (handling large databases of packages).
- 1 mark for discussing reliability/robustness of using pre-tested solutions.

Paper 2 Option D

Answer all questions from the selected option.
3 Question · 45 marks
Question 1 · Option Scenario
15 marks
An agricultural logistics company, **GreenHarvest**, manages shipments of organic produce. To monitor transport conditions, they are developing an object-oriented tracking system in Java.

The system uses a base class `CargoContainer` to represent standard cargo and a subclass `RefrigeratedContainer` to represent temperature-controlled units.

(a) State **one** advantage of using inheritance in object-oriented programming, and explain how it applies to the relationship between `CargoContainer` and `RefrigeratedContainer`. [4]

(b) Draw a UML class diagram showing the relationship between `CargoContainer` and `RefrigeratedContainer`. Include the following details:
- `CargoContainer` has private fields `containerID` (String) and `maxWeight` (double), and a public constructor.
- `RefrigeratedContainer` has a private field `targetTemp` (double), a public constructor, and a public method `isTemperatureSafe(double currentTemp)` that returns a boolean. [5]

(c) Write the Java code for the `RefrigeratedContainer` class. The constructor should initialize all variables (including those inherited from `CargoContainer`). The `isTemperatureSafe` method should return `true` if the `currentTemp` is within \(\pm 2.0\) degrees (inclusive) of the `targetTemp`, and `false` otherwise. [6]
Show answer & marking scheme

Worked solution

### Part (a)
One advantage of inheritance is **code reusability** and the elimination of redundant declarations.
In the context of GreenHarvest, `RefrigeratedContainer` inherits general fields such as `containerID` and `maxWeight` from `CargoContainer` without needing to redefine them. This allows development to focus purely on specialized attributes such as temperature tracking, reducing development time and simplifying code maintenance.

### Part (b)
```
+-----------------------------------------------+
| CargoContainer |
+-----------------------------------------------+
| - containerID : String |
| - maxWeight : double |
+-----------------------------------------------+
| + CargoContainer(String, double) |
+-----------------------------------------------+
^
| [Inheritance Arrow: hollow triangle point]
|
+-----------------------------------------------+
| RefrigeratedContainer |
+-----------------------------------------------+
| - targetTemp : double |
+-----------------------------------------------+
| + RefrigeratedContainer(String, double, double)|
| + isTemperatureSafe(double) : boolean |
+-----------------------------------------------+
```

### Part (c)
```java
public class RefrigeratedContainer extends CargoContainer {
private double targetTemp;

public RefrigeratedContainer(String containerID, double maxWeight, double targetTemp) {
super(containerID, maxWeight);
this.targetTemp = targetTemp;
}

public boolean isTemperatureSafe(double currentTemp) {
return Math.abs(currentTemp - this.targetTemp) <= 2.0;
}
}
```

Marking scheme

### Part (a) [4 marks]
- **1 mark** for stating an advantage of inheritance (e.g., code reuse, modularity, lower redundancy).
- **1 mark** for explaining that advantage clearly.
- **1 mark** for identifying the specific superclass-subclass relationship (`CargoContainer` is superclass, `RefrigeratedContainer` is subclass).
- **1 mark** for demonstrating how fields like `containerID` are shared without duplication.

### Part (b) [5 marks]
- **1 mark** for two correct class box headers showing proper class names.
- **1 mark** for correct fields with private modifier (-) and correct data types.
- **1 mark** for correct methods/constructors with public modifier (+).
- **1 mark** for indicating correct types/return types in methods.
- **1 mark** for using the correct inheritance notation (solid line with an open/hollow arrowhead pointing to `CargoContainer`).

### Part (c) [6 marks]
- **1 mark** for correct class declaration `public class RefrigeratedContainer extends CargoContainer`.
- **1 mark** for declaring private double field `targetTemp`.
- **1 mark** for correct constructor signature matching parameters.
- **1 mark** for correct use of `super(containerID, maxWeight)` as the first statement in the constructor.
- **1 mark** for initializing `this.targetTemp = targetTemp`.
- **1 mark** for implementing `isTemperatureSafe` using `Math.abs(currentTemp - targetTemp) <= 2.0` (or equivalent range checking).
Question 2 · Option Scenario
15 marks
A fitness center chain, **FitLife**, runs a membership management system. To handle billing, the application defines a base class `Membership` and a subclass `PremiumMembership`.

(a) Distinguish between *method overloading* and *method overriding* in the context of this membership system. Provide a brief theoretical example of how each could be used. [4]

(b) The `Membership` class contains a method `calculateMonthlyFee()` which returns a double. The subclass `PremiumMembership` overrides this method to add the cost of extra amenities.

Explain **two** benefits of using polymorphism to store different types of memberships in a single array of type `Membership[]` and processing their fees dynamically. [4]

(c) Write a Java method `calculateTotalRevenue(Membership[] members)` that takes an array of `Membership` objects as a parameter. The method should iterate through the array, calculate the total fees by calling `calculateMonthlyFee()` on each non-null membership, and return this total as a `double`. [7]
Show answer & marking scheme

Worked solution

### Part (a)
- **Method overloading** occurs within the same class when multiple methods share the same name but have different signatures (different number, type, or order of parameters). Example: A class could define `addMembership(String memberName)` and `addMembership(String memberName, double promotionDiscount)`.
- **Method overriding** occurs when a subclass implements a method that is already declared in its superclass, keeping identical parameters and return type. Example: `PremiumMembership` overrides `calculateMonthlyFee()` defined in `Membership` to implement its custom premium pricing logic.

### Part (b)
1. **Extensibility**: It allows the introduction of new membership types (e.g., `VIPMembership`) without changing the core fee calculation logic. The program automatically calls the appropriate subclass method through dynamic binding.
2. **Reduced Code Complexity**: A single loop traversing one uniform array (`Membership[]`) can handle billing for all types of memberships, eliminating the need for multiple loops or conditional `instanceof` checks.

### Part (c)
```java
public double calculateTotalRevenue(Membership[] members) {
double total = 0.0;
if (members != null) {
for (int i = 0; i < members.length; i++) {
if (members[i] != null) {
total += members[i].calculateMonthlyFee();
}
}
}
return total;
}
```

Marking scheme

### Part (a) [4 marks]
- **1 mark** for defining method overloading correctly (same name, different signature, same class).
- **1 mark** for a valid example of overloading.
- **1 mark** for defining method overriding correctly (same name, same signature, different class in hierarchy).
- **1 mark** for a valid example of overriding.

### Part (b) [4 marks]
- **2 marks** for explaining the benefit of extensibility/scalability (adding new subclasses with no change to processing code).
- **2 marks** for explaining simplicity/cleanliness of code (avoiding multiple arrays, typecasting, and explicit conditional logic).

### Part (c) [7 marks]
- **1 mark** for correct method header returning a `double` and accepting `Membership[]` parameter.
- **1 mark** for declaring and initializing a total revenue accumulator variable (e.g., `double total = 0.0;`).
- **1 mark** for checking if the input array itself is null.
- **1 mark** for a correct loop that traverses from index `0` to `members.length - 1`.
- **1 mark** for a null-safety check verifying that `members[i] != null`.
- **1 mark** for correctly calling the `calculateMonthlyFee()` method on elements.
- **1 mark** for returning the accumulated total at the end of execution.
Question 3 · Option Scenario
15 marks
An eco-friendly car rental agency, **EcoDrive**, manages a fleet of hybrid cars. Their software system models vehicles, trips, and drivers using object-oriented principles.

(a) Explain the differences between **aggregation** and **composition** as relationships between classes. Use the concepts of a `HybridCar`, an `ElectricMotor`, and a `Driver` to illustrate your answer. [4]

(b) Discuss how **encapsulation** is implemented in Java, identifying **two** specific keywords/features and explaining how they protect the internal state of a class. [4]

(c) The `HybridCar` class contains an array of `Trip` objects. Each `Trip` object stores the distance traveled and the fuel consumed for a single journey.

Write the code for:
1. The complete `Trip` class, containing private fields `distance` (double) and `fuelUsed` (double), a constructor, and public getter methods. [3]
2. A method `getAverageFuelEfficiency(Trip[] trips)` to be included in the `HybridCar` class. This method must calculate and return the average fuel efficiency (liters per 100 kilometers) across all trips in the array using the formula:
\[\text{Efficiency} = \left( \frac{\text{Total Fuel Used}}{\text{Total Distance}} \right) \times 100\]
You may assume that the array is not null, contains at least one trip, and total distance is greater than 0. [4]
Show answer & marking scheme

Worked solution

### Part (a)
- **Composition** represents a strong ownership relationship where the lifetime of the part is entirely dependent on the lifetime of the whole. If the whole object is destroyed, the part is also destroyed. For example, the relationship between `HybridCar` and `ElectricMotor` is composition; an electric motor is manufactured as an integral part of the car, and if the car is deleted from the system, its motor has no meaningful independent existence.
- **Aggregation** represents a weaker, independent relationship where the part can exist even if the whole is destroyed. For example, the relationship between `HybridCar` and `Driver` is aggregation; a driver can rent different cars, and if a particular `HybridCar` is removed from the fleet database, the `Driver` object remains unaffected.

### Part (b)
Encapsulation is the bundling of data and the methods that operate on that data into a single unit (class), while restricting direct access to some components.
- **`private` modifier**: Restricts field access so that variables can only be read or modified within the declaring class, preventing external entities from corrupting data directly.
- **Accessors/Mutators (Getters/Setters)**: Provide controlled entry points to access or modify fields. Mutators can include data validation, ensuring that the object's state remains consistent (e.g., rejecting negative fuel values).

### Part (c)
**1. Trip Class**
```java
public class Trip {
private double distance;
private double fuelUsed;

public Trip(double distance, double fuelUsed) {
this.distance = distance;
this.fuelUsed = fuelUsed;
}

public double getDistance() {
return this.distance;
}

public double getFuelUsed() {
return this.fuelUsed;
}
}
```

**2. Average Fuel Efficiency Method**
```java
public double getAverageFuelEfficiency(Trip[] trips) {
double totalDistance = 0.0;
double totalFuel = 0.0;
for (int i = 0; i < trips.length; i++) {
totalDistance += trips[i].getDistance();
totalFuel += trips[i].getFuelUsed();
}
return (totalFuel / totalDistance) * 100.0;
}
```

Marking scheme

### Part (a) [4 marks]
- **1 mark** for defining composition as a strong relationship where the part cannot exist without the whole.
- **1 mark** for applying composition correctly to `HybridCar` and `ElectricMotor`.
- **1 mark** for defining aggregation as a weak relationship where the part exists independently.
- **1 mark** for applying aggregation correctly to `HybridCar` and `Driver`.

### Part (b) [4 marks]
- **1 mark** for identifying the `private` access modifier.
- **1 mark** for explaining how `private` restricts direct attribute access.
- **1 mark** for identifying getters/setters (accessors/mutators).
- **1 mark** for explaining how getters/setters offer validation or read-only control over the class state.

### Part (c) [7 marks]
**Trip Class [3 marks]:**
- **1 mark** for defining private `distance` and `fuelUsed` fields with correct types.
- **1 mark** for a correct constructor initializing both fields.
- **1 mark** for both public getter methods returning the attributes.

**Method [4 marks]:**
- **1 mark** for declaring and initializing double accumulators for total distance and total fuel.
- **1 mark** for a standard loop that correctly loops through the `trips` array.
- **1 mark** for retrieving and adding values using the correct getter methods (`getDistance()` and `getFuelUsed()`).
- **1 mark** for computing and returning the correct efficiency calculation based on the formula: `(totalFuel / totalDistance) * 100.0`.

Wondering how well you actually know this?

Thinka is an AI practice app for DSE students — unlimited questions, instant auto-marking, and detailed step-by-step solutions. 100,000+ students use it to confirm they actually know it, not just think they do.

Want more questions like this? Practice unlimited on Thinka — instant answers included.

Start Practising Free