IB DP · Thinka 原創模擬試題

2024 IB DP Computer Science 模擬試題連答案詳解

Thinka Nov 2024 SL IB Diploma Programme-Style Mock — Computer Science

115 150 分鐘2024
An original Thinka practice paper modelled on the structure and difficulty of the Nov 2024 SL IB Diploma Programme Computer Science paper. Not affiliated with or reproduced from IB.

卷一 甲部

Answer all questions. This section contains short-answer and structured questions testing standard core topics.
10 題目 · 25
題目 1 · Short Answer
2.5
Explain why direct observation of users is often preferred over interviews when an analyst is gathering requirements for a new supermarket checkout system.
查看答案詳解

解題

Direct observation involves an analyst watching users perform tasks in their natural work environment. This method is preferred for systems like supermarket checkouts because:
1. It removes human bias: In interviews, checkout operators might forget small steps or exaggerate difficulties. Observation captures exact, objective workflows.
2. It highlights physical constraints: The analyst can see physical barriers (e.g., reaching for items, layout issues) that are difficult to explain in words.
3. It reveals real-time bottlenecks: High-traffic periods and actual queue behaviors are observed directly rather than being estimated hypothetically.

評分準則

Award marks as follows up to a maximum of 2.5 marks:
- 1 mark: For identifying that direct observation captures objective/unbiased data or avoids self-reporting errors.
- 1 mark: For explaining that it reveals physical context, environmental constraints, or real-time bottlenecks (e.g., scanning speeds, physical posture, layout issue).
- 0.5 marks: For linking the explanation explicitly to the supermarket checkout context (e.g., scanner interaction, queue handling).
題目 2 · Short Answer
2.5
Describe the specific role of the Program Counter (PC) and its interaction with the Memory Address Register (MAR) during the fetch stage of the machine instruction cycle.
查看答案詳解

解題

In the fetch stage:
1. The Program Counter (PC) holds the address of the next instruction that needs to be retrieved from memory.
2. This address is copied from the PC to the Memory Address Register (MAR) via the internal bus.
3. The MAR then places this address on the address bus to point to the correct location in primary memory (RAM).
4. Concurrently, the PC is incremented (by 1 or the instruction width) so that it is ready to point to the next instruction in sequence.

評分準則

Award marks as follows up to a maximum of 2.5 marks:
- 1 mark: Correctly stating that the PC holds the address of the next instruction.
- 1 mark: Explaining the transfer of the address from the PC to the MAR (to locate it in primary memory).
- 0.5 marks: Mentioning that the PC is incremented during or immediately after this transfer to point to the next sequential instruction.
題目 3 · Short Answer
2.5
Explain how data collisions are handled in a CSMA/CD (Carrier Sense Multiple Access with Collision Detection) network once a collision has been detected.
查看答案詳解

解題

CSMA/CD manages collisions using the following steps:
1. Collision Detection: Transmitting nodes continuously monitor the line. If two signals overlap, a collision is detected.
2. Transmission Cessation & Jam Signal: The nodes immediately stop transmitting normal data and broadcast a high-voltage 'jam signal' to ensure all other devices on the network recognize that a collision has occurred.
3. Random Back-off: Each transmitting node calculates a random delay time (back-off algorithm) and waits for this duration before checking the line (carrier sensing) to attempt retransmission.

評分準則

Award marks as follows up to a maximum of 2.5 marks:
- 1 mark: For explaining that transmitting nodes halt regular transmission and broadcast a jam/warning signal.
- 1 mark: For explaining that nodes wait for a random back-off time before trying again.
- 0.5 marks: For noting that the random nature of the back-off period prevents immediate re-collision.
題目 4 · Short Answer
2.5
Distinguish between a static array and a dynamic array in terms of memory allocation and execution efficiency.
查看答案詳解

解題

1. Memory Allocation: A static array has its size fixed at compile time (or declaration time), allocating a permanent contiguous block of memory. A dynamic array allocates memory on the heap and can change size dynamically during runtime.
2. Execution Efficiency: Static arrays offer highly consistent execution times and constant \(O(1)\) access/updating speed without overhead. Dynamic arrays also support \(O(1)\) access, but resizing operations can cause sudden execution delays (often \(O(n)\) time) because a new, larger block of memory must be allocated and all existing elements must be copied over.

評分準則

Award marks as follows up to a maximum of 2.5 marks:
- 1 mark: For identifying memory allocation differences (static is fixed-size at compile time/stack; dynamic is resizable at runtime/heap).
- 1 mark: For discussing execution efficiency differences (static has zero resizing overhead; dynamic can suffer from \(O(n)\) performance overhead during size expansion/element copying).
- 0.5 marks: For the correct use of technical terminology (such as compile-time vs run-time, or \(O(1)\) vs \(O(n)\) complexity).
題目 5 · Short Answer
2.5
Compare a direct changeover to a phased introduction when deploying a new hospital patient management system.
查看答案詳解

解題

Direct Changeover involves shutting down the old system and turning on the new system overnight. It is cost-effective and immediate but highly risky because if the new system fails, there is no backup, which is extremely dangerous in a hospital setting where patient lives depend on continuous data access.

Phased Introduction involves rolling out the new system in phases (e.g., starting with the pediatrics department, then cardiology, and so on). This is much safer because any critical failures are restricted to a single department, though it requires maintaining compatibility between the old and new systems during the transition.

評分準則

Award marks as follows up to a maximum of 2.5 marks:
- 1 mark: For explaining direct changeover and highlighting its high risk (no fall-back option if it fails) within a critical context like a hospital.
- 1 mark: For explaining phased introduction and highlighting its safety benefit (bug isolation, gradual training).
- 0.5 marks: For explicitly contextualizing the response to a hospital environment (e.g., patient records, critical safety, department-by-department rollout).
題目 6 · Short Answer
2.5
Explain why using a Virtual Private Network (VPN) is essential for maintaining data confidentiality when accessing online bank accounts over a public Wi-Fi network.
查看答案詳解

解題

When using public Wi-Fi, there is a risk of 'packet sniffing' (man-in-the-middle attacks) where hackers intercept data transmitted through the air because public Wi-Fi is frequently unencrypted or poorly secured.

A VPN mitigates this by:
1. Creating an encrypted 'tunnel' between the user's device and the VPN gateway.
2. Encrypting all outgoing data before it leaves the device, so even if packets are intercepted on the public network, they appear as unreadable ciphertext.
3. Making it impossible for an interceptor to extract sensitive credentials (like banking passwords or session tokens).

評分準則

Award marks as follows up to a maximum of 2.5 marks:
- 1 mark: For describing the risk associated with public Wi-Fi (lack of encryption, potential for packet sniffing/man-in-the-middle attacks).
- 1 mark: For explaining how a VPN resolves this through end-to-end encryption or a secure tunnel.
- 0.5 marks: For linking the explanation to sensitive banking data confidentiality (e.g., ensuring login credentials or transactions cannot be read if intercepted).
題目 7 · Short Answer
2.5
Deduce why a binary search is highly efficient compared to a linear search, specifically in terms of time complexity and search space reduction.
查看答案詳解

解題

Binary search is highly efficient because:
1. Search Space Reduction: With each comparison at the midpoint, binary search discards half of the remaining elements. This divide-and-conquer approach shrinks the search space exponentially.
2. Time Complexity: This halving action translates to a logarithmic time complexity of \(O(\log n)\) in the worst and average cases. Conversely, linear search scans elements one-by-one, resulting in a linear time complexity of \(O(n)\).
3. Scale Impact: For a list of size \(n = 1,000,000\), binary search requires a maximum of only 20 comparisons, while linear search may require up to 1,000,000 comparisons.

評分準則

Award marks as follows up to a maximum of 2.5 marks:
- 1 mark: For explaining the halving/divide-and-conquer mechanism of binary search (and mentioning that the array must be sorted).
- 1 mark: For comparing the time complexities (\(O(\log n)\) for binary search versus \(O(n)\) for linear search).
- 0.5 marks: For providing a clear comparative metric or numerical example (e.g., comparing worst-case performance on a large dataset).
題目 8 · Short Answer
2.5
Simplify the Boolean expression \(A \cdot (A + B)\) to its simplest form using Boolean algebra laws, showing each major step.
查看答案詳解

解題

To simplify \(A \cdot (A + B)\):
1. Apply Distributive Law:
\(A \cdot (A + B) = (A \cdot A) + (A \cdot B)\)
2. Apply Idempotent Law (since \(A \cdot A = A\)):
\(= A + (A \cdot B)\)
3. Apply Distributive Law/Factoring:
\(= A \cdot (1 + B)\)
4. Apply Identity/Annihilation Law (since \(1 + B = 1\)):
\(= A \cdot 1\)
5. Apply Identity Law (since \(A \cdot 1 = A\)):
\(= A\)

Alternatively, this is directly simplified to \(A\) by the Absorption Law: \(A \cdot (A + B) = A\).

評分準則

Award marks as follows up to a maximum of 2.5 marks:
- 1 mark: Showing intermediate expansion using the distributive law, leading to \((A \cdot A) + (A \cdot B)\) or identifying it directly as the Absorption Law.
- 1 mark: Simplifying \(A \cdot A\) to \(A\) resulting in \(A + (A \cdot B)\) and showing how \(A\) is factored to \(A \cdot (1 + B)\).
- 0.5 marks: Reaching the correct final answer of \(A\) with clear, correct notation.
題目 9 · Short Answer
2.5
Explain one advantage and one disadvantage of implementing software using the Software as a Service (SaaS) model rather than an on-premise installation.
查看答案詳解

解題

SaaS hosting shifts the burden of maintenance, infrastructure, and updates to the service provider, which reduces the upfront cost for the client organization (Advantage). However, because the application and data reside on the cloud, the organization requires stable internet access to operate and relinquishes direct control over data security (Disadvantage).

評分準則

Award up to 2.5 marks as follows: [1 mark] for clearly explaining a valid advantage (e.g., lower initial costs, automatic updates, easier scalability). [1 mark] for clearly explaining a valid disadvantage (e.g., reliance on internet access, data privacy/security concerns, limited customization). [0.5 marks] for explicitly comparing the SaaS cloud-hosted nature with the on-premise nature to justify the points.
題目 10 · Short Answer
2.5
Describe how the Program Counter (PC) and the Memory Address Register (MAR) collaborate during the fetch stage of the machine instruction cycle.
查看答案詳解

解題

During the fetch stage, the CPU must locate the next instruction in RAM. The Program Counter (PC) holds the memory address of this instruction. This address is copied to the Memory Address Register (MAR). The MAR then places this address on the address bus to signal RAM. Simultaneously, the PC is incremented by the control unit to hold the address of the next sequential instruction in memory.

評分準則

Award up to 2.5 marks as follows: [1 mark] for stating that the memory address held in the Program Counter (PC) is copied to the Memory Address Register (MAR). [1 mark] for stating that the PC is incremented to prepare for the next cycle. [0.5 marks] for explaining that the MAR holds this address to enable retrieval of the instruction from RAM via the address bus.

卷一 乙部

Answer all questions. This section contains longer, scenario-based structured questions and algorithmic pseudocode tasks.
3 題目 · 45
題目 1 · Structured Explanation
15
A healthcare clinic manages daily patient appointments. The clinic uses a computerized system where two parallel arrays of size \(N\), named `PATIENT_NAMES` and `APPOINTMENT_HOURS`, store the data. The array `APPOINTMENT_HOURS` stores integer values representing scheduled hours (e.g., 9, 10, 14, 15) and is sorted in ascending order. (a) Outline the role of a compiler in executing this patient management program on a computer system. [3 marks] (b) Explain one advantage and one disadvantage of using parallel arrays to store patient names and appointment times rather than using an array of objects. [4 marks] (c) Construct a pseudocode algorithm using a binary search to find the index of a patient scheduled at a target hour `targetHour`. The algorithm should return the index of the hour if found, or -1 if the hour is not scheduled. Assume the length of the arrays is given as \(N\). [5 marks] (d) Explain how the time complexity of a binary search compares to a linear search in both average and worst-case scenarios. [3 marks]
查看答案詳解

解題

(a) A compiler translates the entire high-level source code of the patient management program into machine code (object code) in a single batch before execution. It scans the entire code for syntax errors and reports them; execution cannot proceed until all syntax errors are resolved. The compiled machine code runs directly and efficiently on the target hardware without further translation. (b) One advantage of parallel arrays is that they are straightforward to implement in simpler programming languages that do not support records or object-oriented structures, and they have minimal memory overhead as there are no object-wrapper structures. One disadvantage is that they are highly error-prone to maintain; if one array is sorted, updated, or has items deleted without applying the identical modifications to the corresponding indices of the other array, the relationship between patient names and their appointment times is lost. (c) An appropriate pseudocode algorithm is: function searchHour(APPOINTMENT_HOURS, targetHour, N) low = 0; high = N - 1; found = false; index = -1; while low <= high and found == false do mid = (low + high) div 2; if APPOINTMENT_HOURS[mid] == targetHour then found = true; index = mid; else if targetHour < APPOINTMENT_HOURS[mid] then high = mid - 1; else low = mid + 1; end if; end if; end while; return index; end function. (d) Binary search has a time complexity of \(O(\log_2 N)\) in both average and worst cases because it divides the search space in half with each iteration. In contrast, linear search has a time complexity of \(O(N)\) in average and worst cases because it checks elements sequentially. As \(N\) grows, binary search is vastly more efficient than linear search.

評分準則

(a) Award up to [3 marks]: 1 mark for stating that translation of the entire source code into machine code occurs as a single process before execution. 1 mark for mentioning that syntax errors are checked and reported collectively, preventing compilation if any exist. 1 mark for stating that the executable output runs faster than interpreted code. (b) Award up to [4 marks]: 1 mark for identifying a valid advantage (e.g., ease of implementation in non-OOP languages or reduced memory overhead). 1 mark for explaining that advantage. 1 mark for identifying a valid disadvantage (e.g., risk of data desynchronization). 1 mark for explaining how an unsynchronized index modification ruins data integrity. (c) Award up to [5 marks] for the pseudocode: 1 mark for initializing search boundaries correctly (low = 0, high = N - 1) and defining loop condition (low <= high). 1 mark for calculating the middle index correctly using integer division. 1 mark for comparing the midpoint value with targetHour and handling the match case (setting found to true or assigning index). 1 mark for correctly adjusting the low or high pointers based on the comparison. 1 mark for returning the correct index or -1 if not found. (d) Award up to [3 marks]: 1 mark for stating that binary search has a logarithmic time complexity of \(O(\log_2 N)\). 1 mark for stating that linear search has a linear time complexity of \(O(N)\). 1 mark for explaining that as \(N\) increases, binary search performs significantly fewer comparisons because it repeatedly discards half of the search space, whereas linear search checks elements one by one.
題目 2 · Structured Explanation
15
A university plans to upgrade its network infrastructure to support a hybrid learning environment. Remote students must securely access confidential academic and grading systems hosted on the campus servers. (a) Explain the function of data packets in a packet-switching network used during remote access. [4 marks] (b) Outline how a Virtual Private Network (VPN) provides a secure communication channel for remote students. [4 marks] (c) Identify two factors that may cause network congestion and affect the speed of access to the university's servers, explaining the impact of each. [4 marks] (d) Distinguish between a Wide Area Network (WAN) and a Local Area Network (LAN) in terms of geographical scope and ownership. [3 marks]
查看答案詳解

解題

(a) In a packet-switching network, data sent by a remote student is divided into smaller units called packets. Each packet contains a payload (actual data) and a header containing control information (source IP, destination IP, packet sequence number). Routers dynamically guide each packet independently along the most efficient available paths. At the destination, the receiving server uses the sequence numbers to reassemble the packets in their correct order and requests retransmission of any lost packets. (b) A VPN establishes a secure connection by first authenticating the remote student's identity. It then uses tunneling protocols to encapsulate user data packets inside outer carrier packets. The payload is encrypted using robust algorithms, ensuring that if data is intercepted over the public internet, it remains completely unreadable. It also ensures data integrity, verifying that no data has been modified in transit. (c) Two factors causing network congestion: 1. Available bandwidth constraints: If the external network link to the university has limited bandwidth and many students access large files concurrently, packets queue up, leading to high latency and dropped packets. 2. Hardware bottlenecks: Core switches or routers handling high traffic volumes may run out of buffer memory, leading to packet loss and requiring retransmissions, which further slows down access. (d) LANs cover limited geographical areas like a single building or a campus, whereas WANs span large geographical regions, connecting different cities or countries. Additionally, LANs are typically privately owned and operated by a single entity (such as the university), while WANs rely on public or leased infrastructure provided by telecommunications carriers.

評分準則

(a) Award up to [4 marks]: 1 mark for explaining that data is divided into small, manageable units called packets. 1 mark for identifying the components of a packet (header with routing/sequencing info, payload). 1 mark for explaining that packets are routed independently through the network. 1 mark for explaining reassembly at the destination using sequence numbers. (b) Award up to [4 marks]: 1 mark for mentioning authentication to verify authorized access. 1 mark for explaining encapsulation (tunneling) of packets. 1 mark for explaining encryption of the data payload. 1 mark for explaining data integrity checking to prevent tampering. (c) Award up to [4 marks]: 1 mark for identifying factor 1 (e.g., insufficient bandwidth) and 1 mark for explaining its impact (e.g., data queues, delay under heavy load). 1 mark for identifying factor 2 (e.g., hardware/router bottlenecks or collisions) and 1 mark for explaining its impact (e.g., packet dropping and transmission retries). (d) Award up to [3 marks]: 1 mark for contrasting geographical scale (LAN is local/small, WAN is wide/large). 1 mark for contrasting ownership (LAN is owned by one organization, WAN uses leased telecommunication lines). 1 mark for a clear summarizing distinction (e.g., a WAN connects multiple distinct LANs).
題目 3 · Algorithmic Design
15
An automated warehouse management system tracks items across different physical bins using parallel arrays: BIN_IDS (an array of strings representing unique bin codes, e.g., 'B-1024'), STOCK_LEVELS (an array of integers representing current stock), and REORDER_LEVELS (an array of integers representing the threshold quantity at which stock must be reordered). Part (a): Explain how the system could use validation techniques to ensure that a newly entered bin ID, which must consist of the character 'B', followed by a hyphen '-', and exactly 4 digits (e.g., 'B-4021'), is valid before searching the array. [3 marks] Part (b): Construct an algorithm in pseudocode to perform a linear search on BIN_IDS to find the index of a search term TARGET_ID. The array has N elements. The algorithm should output the index if found, or output an appropriate error message if the ID is not in the list. [4 marks] Part (c): Construct an algorithm in pseudocode that: (1) Iterates through parallel arrays BIN_IDS, STOCK_LEVELS, and REORDER_LEVELS (of size N). (2) Identifies all bins where the stock level is strictly less than the reorder level. (3) Stores the corresponding bin IDs into a new array named LOW_STOCK_BINS. (4) Counts the total number of low-stock bins. (5) Outputs the populated LOW_STOCK_BINS array elements and the total count. [8 marks]
查看答案詳解

解題

Part (a): The system can apply three validation checks. First, a Length Check ensures the input string is exactly 6 characters long. Second, a Format or Pattern Check verifies that the first character is 'B' and the second character is '-'. Third, a Type or Range Check ensures that the remaining four characters (from index 2 to 5) are numeric digits. Part (b): Pseudocode for Linear Search: FOUND = false; I = 0; INDEX = -1; loop while (I < N) and (FOUND = false); if BIN_IDS[I] = TARGET_ID then FOUND = true; INDEX = I; else I = I + 1; end if; end loop; if FOUND = true then output 'Target found at index: ', INDEX; else output 'Error: Target ID not found.'; end if. Part (c): Pseudocode for Stock Checking: LOW_COUNT = 0; loop I from 0 to N - 1; if STOCK_LEVELS[I] < REORDER_LEVELS[I] then LOW_STOCK_BINS[LOW_COUNT] = BIN_IDS[I]; LOW_COUNT = LOW_COUNT + 1; end if; end loop; output 'Total low stock bins: ', LOW_COUNT; loop J from 0 to LOW_COUNT - 1; output LOW_STOCK_BINS[J]; end loop.

評分準則

Part (a) [3 marks]: Award [1 mark] for explaining the use of a length check to verify the input is exactly 6 characters. Award [1 mark] for explaining a format/pattern check to verify the first character is 'B' and the second is '-'. Award [1 mark] for explaining a character-type check to verify that the last 4 characters are numeric. Part (b) [4 marks]: Award [1 mark] for initializing loop control variables and search state correctly. Award [1 mark] for a loop structure that iterates safely through N elements and terminates early if the target is found. Award [1 mark] for comparing the elements correctly and updating the flag. Award [1 mark] for appropriate output handling for both successful and unsuccessful search results. Part (c) [8 marks]: Award [1 mark] for initializing the count pointer (LOW_COUNT = 0) correctly. Award [1 mark] for a correct loop traversing the arrays from index 0 to N-1. Award [1 mark] for testing the condition STOCK_LEVELS[I] < REORDER_LEVELS[I] using the correct comparison operator. Award [1 mark] for referencing parallel arrays using a common index variable (I). Award [1 mark] for assigning the matching bin ID to LOW_STOCK_BINS. Award [1 mark] for using LOW_COUNT as the array index pointer for LOW_STOCK_BINS to ensure dense insertion. Award [1 mark] for incrementing the counter only when a low-stock match is found. Award [1 mark] for outputting both the final count and looping to output the low-stock bin IDs.

卷二 Option D (OOP)

Answer all questions from this option. This option tests Object-Oriented Programming concepts, UML modeling, and Java implementations.
3 題目 · 45
題目 1 · OOP Implementation & UML Modeling
15
A smart environmental monitoring system uses a gateway to manage data collected from different types of sensors.

All sensors have an ID (String) and a battery level (double percentage). Subclasses represent specific types of sensors, such as `TemperatureSensor` (which contains an additional attribute for current temperature in Celsius) and `MoistureSensor` (which contains an additional attribute for soil moisture percentage).

(a) Describe the UML class diagram representing the system. Your description must include class names, attributes (with visibility), inheritance relationships, and the association between a managing `Gateway` class and the `Sensor` class. [4]

(b) State two advantages of using inheritance in this scenario. [2]

(c) Construct the abstract class `Sensor` in Java. Include its instance variables, a constructor, accessor methods, and the declaration of an abstract method `readData()` which returns a double. [4]

(d) Implement the `Gateway` class in Java. It should contain an array of `Sensor` objects with a maximum capacity of 100 sensors and an integer to track the active sensor count. Implement a method `calculateAverageTemperature()` that processes the array and returns the average temperature from all `TemperatureSensor` objects currently managed by the gateway. If no temperature sensors exist, return 0.0. [5]
查看答案詳解

解題

(a) UML Design:
- Class `Sensor` {abstract}: Private attributes: `id` (String), `batteryLevel` (double). Public methods: Constructor, `getId()`, `getBatteryLevel()`, abstract method `readData()` returning double.
- Class `TemperatureSensor` inherits from `Sensor` (indicated by an inheritance arrow pointing to `Sensor`). Private attribute: `temperature` (double). Public methods: Constructor, `readData()` (implements abstract method).
- Class `MoistureSensor` inherits from `Sensor` (indicated by an inheritance arrow pointing to `Sensor`). Private attribute: `moisture` (double). Public methods: Constructor, `readData()` (implements abstract method).
- Class `Gateway` has a composition or aggregation relationship with `Sensor` (indicated by a line from `Gateway` to `Sensor` with a diamond shape at `Gateway` or directed association). Attributes: `sensors` (Sensor array), `sensorCount` (int). Methods: Constructor, `calculateAverageTemperature()` returning double.

(b) Advantages of using inheritance:
1. Code Reusability: Common properties like `id` and `batteryLevel` along with their getters are defined once in the superclass `Sensor` and inherited by both `TemperatureSensor` and `MoistureSensor`, reducing redundancy.
2. Polymorphism: It allows the `Gateway` class to store different types of sensor subclasses in a single uniform array of type `Sensor[]` and process them polymorphically.

(c) Abstract class `Sensor` implementation:
```java
public abstract class Sensor {
private String id;
private double batteryLevel;

public Sensor(String id, double batteryLevel) {
this.id = id;
this.batteryLevel = batteryLevel;
}

public String getId() {
return this.id;
}

public double getBatteryLevel() {
return this.batteryLevel;
}

public abstract double readData();
}
```

(d) `Gateway` class implementation:
```java
public class Gateway {
private Sensor[] sensors;
private int sensorCount;

public Gateway() {
this.sensors = new Sensor[100];
this.sensorCount = 0;
}

public boolean addSensor(Sensor s) {
if (sensorCount < 100) {
sensors[sensorCount] = s;
sensorCount++;
return true;
}
return false;
}

public double calculateAverageTemperature() {
double totalTemp = 0.0;
int tempSensorCount = 0;
for (int i = 0; i < sensorCount; i++) {
if (sensors[i] instanceof TemperatureSensor) {
// Downcasting is performed to access TemperatureSensor specific methods/data
TemperatureSensor ts = (TemperatureSensor) sensors[i];
totalTemp += ts.readData();
tempSensorCount++;
}
}
if (tempSensorCount == 0) {
return 0.0;
}
return totalTemp / tempSensorCount;
}
}
```

評分準則

Part (a) [4 marks]
- 1 mark: Identifying `Sensor` as an abstract superclass with subclasses `TemperatureSensor` and `MoistureSensor` connected via inheritance symbols.
- 1 mark: Specifying attributes with appropriate private (`-`) and public (`+`) modifiers.
- 1 mark: Correct association/aggregation relationship between `Gateway` and `Sensor` (e.g., 1 gateway manages 0..100 sensors).
- 1 mark: Clearly showing the abstract method `readData()` in the parent and its overridden implementations in the subclasses.

Part (b) [2 marks]
- 1 mark per valid advantage up to 2 marks (e.g., code reusability, easier extensibility for adding new sensor types, polymorphism in collections).

Part (c) [4 marks]
- 1 mark: Correct class declaration with the `abstract` keyword.
- 1 mark: Declaring private attributes `id` and `batteryLevel` with correct data types.
- 1 mark: Implementing a parameterized constructor initializing both instance variables.
- 1 mark: Correctly declaring the abstract method `readData()` with the abstract keyword, no body, and a double return type.

Part (d) [5 marks]
- 1 mark: Declaring variables (`Sensor[]` and `sensorCount`) and initializing them correctly in the constructor (capacity 100).
- 1 mark: Implementing a loop that iterates up to `sensorCount` to prevent processing null elements.
- 1 mark: Correctly checking whether a element is an instance of `TemperatureSensor` using `instanceof`.
- 1 mark: Safe downcasting and accumulation of readings from temperature sensors.
- 1 mark: Handling the division-by-zero case and returning the calculated average correctly.
題目 2 · OOP Implementation & UML Modeling
15
A cinema ticketing system manages show bookings. The `Show` class represents a screening and contains the following instance variables:
- `showID` (String)
- `ticketPrice` (double)
- `seatingGrid` (2D boolean array where `true` indicates a seat is booked, and `false` indicates it is empty)

(a) Outline the difference between aggregation and composition relationships using the design of a booking system involving `Show`, `Ticket`, and `Customer` objects as examples. [3]

(b) Construct a Java constructor for the `Show` class that accepts `showID`, `ticketPrice`, `rows`, and `cols` as arguments, initializing the variables and creating a fully empty `seatingGrid` of size `rows` by `cols`. [3]

(c) Write a Java method `bookSeat(int row, int col)` in the `Show` class that attempts to book a seat. The method must check if the requested seat coordinates are within valid bounds. If valid and empty, book the seat (set to `true`) and return `true`. Otherwise, return `false` without modifying any state. [4]

(d) Write a Java method `calculateTotalRevenue()` in the `Show` class that traverses the `seatingGrid` to compute and return the total dollar revenue generated from all booked seats for this show. [5]
查看答案詳解

解題

(a) Aggregation vs. Composition:
- Aggregation represents a "has-a" relationship where the child can exist independently of the parent. For example, a `Customer` has a collection of booked `Ticket`s, but if the `Customer` object is deleted, the dynamic database records of `Ticket`s or the performance event itself can still exist.
- Composition represents a stronger "has-a" relationship where the child cannot exist independently of the parent. For example, the `seatingGrid` or a physical `Seat` is composed within a `Show`. If the `Show` is cancelled/deleted, the corresponding `seatingGrid` or localized physical seat assignments for that specific show are completely destroyed.

(b) Constructor code:
```java
public class Show {
private String showID;
private double ticketPrice;
private boolean[][] seatingGrid;

public Show(String showID, double ticketPrice, int rows, int cols) {
this.showID = showID;
this.ticketPrice = ticketPrice;
this.seatingGrid = new boolean[rows][cols];
// Explicit initialization (optional in Java as boolean defaults to false,
// but highly recommended for demonstrating explicit initialization logic)
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
this.seatingGrid[r][c] = false;
}
}
}
}
```

(c) `bookSeat` implementation:
```java
public boolean bookSeat(int row, int col) {
// Check if row/col are out of bounds
if (row < 0 || row >= seatingGrid.length) {
return false;
}
if (col < 0 || col >= seatingGrid[0].length) {
return false;
}
// Check if the seat is already booked
if (seatingGrid[row][col]) {
return false;
}
// Perform booking
seatingGrid[row][col] = true;
return true;
}
```

(d) `calculateTotalRevenue` implementation:
```java
public double calculateTotalRevenue() {
int bookedSeatsCount = 0;
// Traverse the 2D seatingGrid
for (int r = 0; r < seatingGrid.length; r++) {
for (int c = 0; c < seatingGrid[r].length; c++) {
if (seatingGrid[r][c] == true) {
bookedSeatsCount++;
}
}
}
return bookedSeatsCount * this.ticketPrice;
}
```

評分準則

Part (a) [3 marks]
- 1 mark: Explaining aggregation as a weak relationship with independent life-cycles.
- 1 mark: Explaining composition as a strong ownership relationship where child objects are destroyed with the parent.
- 1 mark: Correct application of both terms to the context (e.g., `Customer` and `Ticket` [aggregation] vs `Show` and `seatingGrid` [composition]).

Part (b) [3 marks]
- 1 mark: Correct constructor header with parameters (`String`, `double`, `int`, `int`).
- 1 mark: Correct initialization of local state fields `showID` and `ticketPrice`.
- 1 mark: Correct instantiation of the 2D boolean array using the dynamic dimensions (`new boolean[rows][cols]`).

Part (c) [4 marks]
- 1 mark: Valid boundary validation logic checking lower limits (0) and upper limits against array dimensions (e.g., `seatingGrid.length` and `seatingGrid[0].length`).
- 1 mark: Checking if the seat is occupied (`seatingGrid[row][col] == true`).
- 1 mark: Setting the value of the grid cell to `true` upon successful booking.
- 1 mark: Returning accurate boolean results (`true` if successful, `false` otherwise).

Part (d) [5 marks]
- 1 mark: Declaring and initializing a counter/revenue accumulator.
- 1 mark: Implementing a nested loop to traverse rows and columns of the 2D array.
- 1 mark: Using correct loop condition bounds (`seatingGrid.length` and `seatingGrid[r].length`).
- 1 mark: Checking condition where element equals `true` correctly inside loops.
- 1 mark: Multiplying total count by `ticketPrice` and returning correct double precision result.
題目 3 · OOP Implementation & UML Modeling
15
A transport and logistics firm tracks the environmental impact of its fleet using an OOP approach.

The system uses an interface `CarbonFootprint` defined as:
```java
public interface CarbonFootprint {
double calculateCarbon();
}
```

Two types of transport exist:
- `ElectricTruck`: defined by `distanceTraveled` (double, miles) and `efficiency` (double, kWh per mile). The carbon produced is calculated as: \( \text{distanceTraveled} \times \text{efficiency} \times 0.38 \).
- `CargoShip`: defined by `distanceTraveled` (double, miles) and `fuelConsumption` (double, gallons per mile). The carbon produced is calculated as: \( \text{distanceTraveled} \times \text{fuelConsumption} \times 10.15 \).

(a) Explain two operational differences between an interface and an abstract class in Java. [3]

(b) Construct the complete Java class `ElectricTruck` implementing the `CarbonFootprint` interface. Include appropriate private instance variables, constructor, and the `calculateCarbon()` method. [5]

(c) A processing class `FleetManager` manages an array of `CarbonFootprint` objects. Construct the method `totalCarbonEmitted(CarbonFootprint[] fleet)` in Java, which iterates through an array of objects that implement `CarbonFootprint` and returns the sum of emissions. Your code must account for the possibility of elements being `null`. [4]

(d) Explain how polymorphism is demonstrated in the implementation of the `totalCarbonEmitted` method. [3]
查看答案詳解

解題

(a) Differences between an interface and an abstract class:
1. Abstract classes can contain instance variables (state) and fully implemented methods, whereas interfaces cannot store state (they can only contain constants) and prior to Java 8, could only declare abstract methods.
2. Java only supports single class inheritance, so a class can extend at most one abstract class, whereas a class can implement multiple interfaces.
3. Abstract classes are typically used for establishing a strict "is-a" hierarchy, while interfaces define a shared capability or behavioral contract ("can-do") across unrelated classes.

(b) `ElectricTruck` implementation:
```java
public class ElectricTruck implements CarbonFootprint {
private double distanceTraveled;
private double efficiency;

public ElectricTruck(double distanceTraveled, double efficiency) {
this.distanceTraveled = distanceTraveled;
this.efficiency = efficiency;
}

@Override
public double calculateCarbon() {
return this.distanceTraveled * this.efficiency * 0.38;
}
}
```

(c) `FleetManager` implementation:
```java
public class FleetManager {
public double totalCarbonEmitted(CarbonFootprint[] fleet) {
double total = 0.0;
if (fleet == null) {
return 0.0;
}
for (int i = 0; i < fleet.length; i++) {
if (fleet[i] != null) {
// Polymorphic invocation
total += fleet[i].calculateCarbon();
}
}
return total;
}
}
```

(d) Demonstration of Polymorphism:
Polymorphism is demonstrated because the loop variable `fleet[i]` is declared as type `CarbonFootprint` (the interface reference), but at runtime, the program dynamically resolves the actual concrete type (such as `ElectricTruck` or `CargoShip`). When `fleet[i].calculateCarbon()` is invoked, JVM calls the specific, overridden version of `calculateCarbon()` corresponding to the actual instance type of that object, rather than relying on a static definition. This decouples the client method from specific concrete subclasses.

評分準則

Part (a) [3 marks]
- 1 mark: Highlighting state difference (instance variables in abstract class vs constants only in interface).
- 1 mark: Highlighting inheritance limits (single inheritance vs multiple interface implementation).
- 1 mark: Highlighting structural intent difference (conceptual "is-a" hierarchy vs functional contract/capability).

Part (b) [5 marks]
- 1 mark: Correct class declaration implementing `CarbonFootprint` interface.
- 1 mark: Private instance fields declared with double precision types.
- 1 mark: Parameterized constructor initializing attributes.
- 1 mark: Method `calculateCarbon()` implemented with correct formula calculation.
- 1 mark: Correct syntax including return statement and public modifier.

Part (c) [4 marks]
- 1 mark: Correct method header accepting array of `CarbonFootprint` objects.
- 1 mark: Checking for null references at the element level before executing method logic.
- 1 mark: Standard array loop traversing through index `0` to `fleet.length - 1`.
- 1 mark: Accumulating the return values from the dynamic method calls and returning the total double value.

Part (d) [3 marks]
- 1 mark: Explaining dynamic binding/runtime resolution of the overridden method.
- 1 mark: Mentioning the interface reference type (`CarbonFootprint`) being used to refer to concrete subclasses.
- 1 mark: Identifying the benefit of decoupling, where adding a new transport type (e.g., `HydrogenTrain`) does not require changing `totalCarbonEmitted()`'s logic.

想知道自己有幾分把握?

Thinka 是 DSE 學生用的 AI 練習應用程式,有無限量練習題、即時自動批改和詳細解題步驟。逾 100,000 名學生用它確認自己真的識,而不只是「以為識」。

想練更多類似題型?在 Thinka 無限量操練,即時知道答案。

免費開始練習