Decorative banner

Option D - Object-oriented programming (OOP)

Question 1

HLPaper 2

Full details of the customers are stored as objects of the Customer class. This class is partially shown below:

public class Customer
{
private String memberId;
private String email; //email address (assume only 1 per customer)
public Customer(String a, String b)
{
memberId = a;
email = b;
}
public String getMemberId()
{
return memberId;
}
public String getEmail()
{
return email;
}
}

The objects can be accessed through the linked list allCustomerswhich is declared in the main (driver) class as follows:

LinkedList<Customer> allCustomers = new LinkedList<Customer>()

1.

Outline why a linked list structure has been chosen for allCustomers.

[2]
2.

Construct the method goldMails()that will return an ArrayListcontaining the email addresses of all current “Gold” members. You should make use of any previously defined methods.

[6]

Question 2

SLPaper 2

The management of the company will launch a new scheme to give every 50th car driver and every 60th motorcyclist a free coffee voucher. The code for printing this voucher has already been created and is activated by calling the static method Vouchers.printCoffeeVoucher().

AgetKind()method has already been added to the Vehicleclass, which returns a charvalue indicating whether it is a car (c) or a motorbike (m).

One test performed on the finished code was defined as follows:

1.

Describe, without writing code, any changes required to the addVehiclemethod and the ParkingAreaclass to make the new voucher scheme work.

[5]
2.

Identify three other tests you might perform on the completed code to prove that it functions correctly.

[3]
3.

The removeVehiclemethod of the ParkingAreaclass searches in the array for a Vehicleobject with a specified registration plate, then removes it by setting that array index to null.

The method returns a reference to the Vehicleobject that has been removed from the array, or nullif no matching registration plate was found.

Construct the removeVehiclemethod.

[6]

Question 3

HLPaper 2

Consider the following recursive method.

**public void** recursionEx(**int** x)
{
**if**(x != 0)
{
System.out.println(x);
recursionEx(x - 1);
System.out.println(x);
}
}

1.

Identify two essential features of a recursive algorithm.

[2]
2.

Copy and complete the following table to show the output when the method is called by: recursionEx(3);

[4]
3.

Explain what would happen if the method was called by recursionEx(-3).

[3]
4.

Identify three features which should be included in either program code or UML diagrams to help programmers understand and modify programs in the future.

[3]

Question 4

SLPaper 2

A generic Event class is defined as follows:

class Event
{
private String eventID;
private int numberOfRaces;
private Race[] races;
private Race finals;
public Event(String ID, int numberOfRaces)
{
eventID = ID;
races = new Race[numberOfRaces];
for(int i = 0; i < numberOfRaces; i++)
{
races[i] = new Race();
}
finals = new Race();
}
public void addSwimmers()
{
// fills the qualifying heats with swimmers
}
public void fillFinals()
{
// fills the finals race with the best 8 from the qualifying heats
}
// more methods()
}

The Event class above assumes that the event has more than 8 swimmers and requires qualifying heats. However, an event with less than 9 swimmers has no qualifying heats, so the original Event class was inherited by a new class FinalsOnlyEvent.

1.

The same method identifier addSwimmersis used in both classes Raceand Event.

Explain why this does not cause a conflict.

[3]
2.

Outline two advantages of the OOP feature “inheritance”.

[4]
3.

Outline how method overriding can help to create the new class FinalsOnlyEvent.

[2]

Question 5

HLPaper 2

The array linein POSlineis now replaced by a singly linked listof CartNodeobjects. The class CartNodehas been defined as follows.

public class CartNode
{
private Cart myCart;
private CartNode next;
public CartNode(Cart aCart)
{
this.myCart = aCart;
this.next = null;
}
public Cart getCart(){ return this.myCart; }
public CartNode getNext(){ return this.next; }
public void setNext(CartNode nextNode)
{
this.next = nextNode;
}
}

The class POSlisthas been implemented with the standard list methods addLastand removeFirstthat act on list.

A method leaveList(int n)is required in the class POSlist, similar to the method leaveLine(int n)that was added to the class POSline.

1.

Define the term object reference.

[2]
2.

Using object references, construct the method public Cart removeFirst()that removes the first CartNodeobject from list. The method must return the Cartobject in that node or nullif listis empty.

[4]
3.

Sketch the linked list listafter running the following code fragment where cart1, cart2, cart3, cart4andcart5have been instantiated as objects of the class Cart.

POSlist queueList = new POSlist()
queueList.addLast(cart2);
queueList.addLast(cart1);
queueList.addLast(cart4);
queueList.removeFirst();
queueList.addLast(cart5);
queueList.addLast(cart3);
queueList.removeFirst();

[2]
4.

Outline one feature of the abstract data structure queue that makes it unsuitable to implement customers waiting in line.

[2]
5.

Using object references, construct the method public Cart leaveList(int n)that removes the nth CartNodeobject from list. The method must return the Cartobject in that node.

You may assume that the nth CartNodeobject exists in the list.
You may use any method declared or developed.

[6]
6.

Explain the importance of using coding style and naming conventions when programming.

[4]

Question 6

SLPaper 2

An airport uses an object-oriented program to keep track of arrivals and departures of planes. There are many objects in this system and some are listed below.

The code below outlines the Arrivalclass used in this program.

public class Flight
{ private String id;
public String getId() {return this.id;}
// ... more variables, accessor and mutator methods
}
**
public class** Arrival
{ private Flight myFlight;
private String sta; // Scheduled Time of Arrival ('hh:mm')
private int runway;
private String gate;
private int delay;
private boolean landed;

public Arrival(Flight myFlight, String sta)
{ **this.**myFlight = myFlight;
**this.**sta = sta;
**this.**runway = 0;
**this.**gate = null;
**this.**delay = 0;
**this.**landed = false;
}

public void addDelay(int newDelay)
{ **this.**delay = newDelay;
}

public String getETA()
{ // calculates the Estimated Time of Arrival (ETA) of the flight
// by adding the delay to the sta and returning the result as a
// String ('hh:mm')
}

public int compareWith(String flightID)
{ if (myFlight.getID().equals(flightID)) { return 0; }
else { return 1; }
}

public int compareWith(Arrival anotherArrival)
{ // missing code
}

// ... plus accessor and mutator methods
}

The code below outlines part of the FlightManagementclass used in this program.

For the purposes of this exam only arriving flights are being considered.

public class FlightManagement
{
private Arrival[] inbound; // array of inbound airplanes
private int last = -1; // index of last used entry
public FlightManagement()
{ inbound = new Arrival[200];
}
public void add(Arrival newArrival)
{ // missing code that adds the newArrival to the array inbound
// sorted by ETA, and updates last
}

private int search (String flightID)
{ // missing code that searches the array inbound and
// returns the index of the Arrival object with flightID
}

public Arrival remove(String flightID)
{ Arrival result;
int index = search(flightID);
result = inbound[index];
while (index < last)
{ inbound[index] = inbound[index + 1];
index++;
}
last--;
return result;
}

// ... many more methods
}

The method searchin the FlightManagementclass searches the array inboundand returns the index of the Arrivalobject with the given flightID.

1.

Outline the general nature of an object.

[2]
2.

Describe two disadvantages of using Object Oriented Programming (OOP).

[4]
3.

Outline one advantage of using modularity in program development.

[2]
4.

State the relationship between the Flightobject and the Arrivalobject.

[1]
5.

Construct a UML diagram to represent theArrivalobject.

[4]
6.

Construct the method searchimplementing a linear search. Use the first compareWith()method in the Arrivalobject.

You may assume that an Arrivalobject with the given flightIDexists in the array inbound.

[4]
7.

Outline one advantage of using a binary search.

[2]
8.

Outline one disadvantage of using a binary search.

[2]

Question 7

SLPaper 2

A company provides car parking services in large cities and needs a computer system to keep track of the number of vehicles using its parking areas.

When a vehicle arrives, its registration plate is recorded on the system and it is allocated a number that identifies where it should park. When the vehicle leaves, that space is made available for other vehicles to use.

Vehicles are identified by their unique registration plate, which is an alphanumeric code of eight characters (e.g. X1234567). This is clearly displayed on the vehicle.

A programmer created the classes ParkingAreaandVehicleto model the above situation.

public class ParkingArea {
private Vehicle vehicles[];
private String name;

ParkingArea(String name, int capacity) {  
    this.name = name;  
    if (capacity > 300) capacity = 300;  
    this.vehicles = new Vehicle\[capacity\];  
}  

String getName() {  
    return name;  
}  
  
public int getCapacity() {  
    return vehicles.length;  
}  

public int findVehicle(String reg) {  
    //find where the vehicle is located in the array and  
    //return the index not yet written  
}  

}

public class Vehicle {
private String registration;
private byte colour;
private boolean broken;

public final static byte BLACK=1;  
public final static byte WHITE=2;  
public final static byte BLUE=3;  
public final static byte RED=4;  
public final static byte GREEN=5;  
private final static double ADMIN\_FEE = 3;  

public Vehicle() {}  

public Vehicle(String registration) {  
    this.registration = registration;  
}  
public Vehicle(String registration, byte colour) {  
    this.registration = registration;  
    this.colour=colour;  
}  
public void setBroken(boolean broken) {  
    this.broken=broken;  
}  
public void setColour(byte colour) {  
    this.colour=colour;  
}  
public boolean getBroken() {  
    return broken;  
}  
public String getRegistration() {  
    return registration;  
}  
public double pay(int hours) {  
    // code to return admin fee - only if applicable  
}  

}

1.

Outline one effect of using the modifier staticwhen declaring a variable.

[2]
2.

Describe the relationship between the classes Vehicleand ParkingArea.

[3]
3.

Outline why it is necessary to use the keyword thisin the setBrokenmethod of the Vehicleclass.

[2]
4.

Construct code to create an instance of the Vehicleclass that has a registration of X1234567.

[2]
5.

Construct code that sets the colour of the object created in part (i) as black.

[2]

Question 8

SLPaper 2

A hotel chain has a loyalty scheme in which customers are awarded 1000 points for each day they stay in one of their hotels. With these points, customers can achieve one of three status levels: Gold, Silver or Bronze. The level will determine the extra services to which they are entitled.

The total number of points collected during the current year will determine which of the three status levels they are assigned for the following year: For example only the points collected in 2018 will determine the status level for 2019.

Occasionally, new customers receive additional bonus points as part of a promotion.

The Pointsclass keeps details of the points and status levels of each customer.

public class Points
{
private String memberId; // id of the hotel customer
private int totalPoints; // this year's points
private int bonusPoints; // any bonus points given to this year's new member
private String statusNow; // current(this year's)status
private String statusNextYear; // following year's status
private Visits[] allVisits = new Visits[366];//details of each visit
// during this year
int y; // number of visits this year
public Points(String id) // constructor for new member
{
memberId = id;
bonusPoints = 0;
y = 0;
statusNow = 'Bronze';
}

//constructor for new member given bonus points (valid for current year only)
public Points(String id, int bp)
{
memberId = id;
bonusPoints = bp; // multiples of 1000 - maximum number is 5000
y = 0;
statusNow = 'Bronze';
}

// all the accessor and mutator methods are present but not shown
public Visits getAllVisits(int v)
{
return allVisits[v];
}
public void addVisit(Visits v) // adds a new Visit object to the array
{
allVisits[y] = v;
y = y + 1;
}

isGold() {code missing}
calculateTotalPoints(){code missing}
daysMissing(){code missing}
}

The instance variables in the Pointsclass are preceded by the modifier private. The choice of modifier affects the way in which these variables are accessed or used.

The customers will be assigned one of three levels for the following year (Gold, Silver or Bronze) depending upon the current year’s total points as follows.

  • Bronze = less than 10 000 points
  • Silver = 10 000 or more but less than 50 000
  • Gold = 50 000 or more.

In 2018, Tim became a member for the first time and was awarded a bonus of 1000 points. So far, in 2018, Tim has stayed three times at one of these hotels. The first visit lasted 2 days, the second visit lasted 1 day and the third visit lasted 6 days.

The different Pointsobjects are stored in an array which is declared globally in the main (driver) class as follows:Points[] allPoints = new Points[10000];

1.

With the use of two examples other than private, outline how the choice of this modifier affects the way in which these variables are accessed or used.

[4]
2.

With reference to the two methods with the same name in the Pointsclass, explain the OOP feature that makes it possible to successfully implement either of these methods.

[4]
3.

State the status level that Tim has been assigned, for 2019, following these visits.

[1]
4.

State how an individual object can be identified using this array.

[1]
5.

The attribute statusNowis assigned its correct value at the beginning of every year for existing members. It cannot be changed during the year.

Construct the method isGold()in the Pointsclass, which will return whether the current status is “Gold”.

[3]

Question 9

SLPaper 2

The array inboundin the FlightManagementclass is sorted by Estimated Time of Arrival (ETA).

1.

Define the term method signature.

[2]
2.

Construct a method showDelayed()that outputs the IDs of all delayed flights in the array inboundthat have not yet landed and that have an ETA before a given time t. The time tis passed as a Stringparameter.

[4]
3.

Without using a sorting algorithm, construct the method add(Arrival newArrival)that inserts a newArrivalin the sorted array inbound. You may assume that newArrivalhas been instantiated and that the array inboundis not full.

[6]
4.

When a flight is delayed, a method in FlightManagementis used to find and update the flight with the delay and to reorganize the array so that it remains sorted for the ET

[4]

Question 10

SLPaper 2

A restaurant uses an object-oriented program to manage the cost of the food and drink consumed by customers. Everytime a table is occupied a Paymentobject is instantiated which will contain details of the items ordered. As each item is ordered, a FoodItemor a DrinkItemobject is added to the Paymentobject as appropriate.

public class Payment
{
private FoodItem[] fi = new FoodItem[100];
private int fiCount;
private static double foodTax = 0.2; // 20 % sales tax added to
// all food prices
private DrinkItem[] di = new DrinkItem[100];
private int diCount;
private static double drinkTax = 0.1; // 10 % sales tax added to
// all drink prices
public Payment()
{
fiCount = 0;
diCount = 0;
}
public DrinkItem getDi(int x)
{
return di[x];
}

// all other accessor and mutator methods are included

// addFoodItem() – this method adds a new FoodItem object
// addDrinkItem() – this method adds a new DrinkItem object

public static double findPrice(Item[] pl, String c)
{ //code missing }

// calculateBill() – This method returns the bill (the total value of
// the items consumed for a particular table)
}

public class FoodItem
{
private String itemCode;
private int quantity;

public FoodItem(String x, int y)
{
itemCode = x;
quantity = y;
}
// all accessor and mutator methods are included
}

The DrinkItemclass is defined in a similar way.

Whenever a Payment object is instantiated, the variables fiCount and diCount are initialized to 0 through the code in the constructor.

1.

Outline an alternative method of initializing these variables that would not require the use of the code in the constructor.

[2]
2.

State the implication of the use of the term staticin the Paymentclass.

[2]
3.

With reference to two examples from the classes in the resource, explain the benefits gained by the use of different data types.

[4]
4.

Describe the purpose of the following statement:

**private** FoodItem[] fi = **new** FoodItem[100]

[3]
5.

The Paymentclass method addFoodItem()is passed a FoodItemobject as a parameter.

Construct the method addFoodItem().

[3]
Jojo

Intern at RevisionDojo this summer!

Gain work experience and make an impact on thousands of students worldwide. Limited spots available.