Problem overview
The task is to build two classes that work together. A LineItem is one row of an order: a product name, a price and a quantity. A Cart holds many rows and adds them up.
LineItemhas public fieldsString name,double priceandint quantity, a constructorLineItem(String name, double price, int quantity)and a methoddouble subtotal()that returnsprice * quantity.Cartkeeps aprivate List<LineItem> items, hasvoid add(LineItem item)to append a row, anddouble total()to return the sum of all the subtotals. An empty cart totals 0.
The driver checks an empty cart, then one subtotal (an apple at price 5, quantity 3, which is 15), then builds a cart with the apple and bread at 20 times 3, and finally adds milk at 10 times 2:
Empty: 0
Subtotal: 15
Total: 75
Total: 95
Approach: composition
A Cart is not a kind of LineItem; it has line items. That relationship is composition: one class stores objects of another class in a field. It splits the work cleanly. A row knows how to compute its own cost, and the cart only knows how to add the costs up by asking each row.
The total is not stored anywhere. total() recomputes it from the rows currently in the list every time it is called, so it can never get out of date. That is why the second Total line in the driver, printed after the milk is added, is larger than the first (95 against 75).
Step by step
- Declare
LineItemfirst, becauseCartuses it. - Add the three public fields:
name(aString),price(adouble) andquantity(anint). A quantity is always whole, and a price may not be. - Write the constructor. It has the class's name and no return type, and takes the three values.
- Store each parameter in its field with
this.. The parameters share the fields' names, sothis.namemeans the field and plainnamemeans the parameter. - Add
subtotal(), returning adouble: the row's price times its quantity. Both are fields of the same object, so nothis.is needed. - Declare
CartbelowLineItem. - Add the private
itemslist, aList<LineItem>that starts as an emptyArrayList. - Write
add, a publicvoidmethod that appends the item withitems.add(item). - Write
total(). Start adouble sumat 0, so an empty cart gives 0. - Loop over the rows with the colon form of
for, and add each row'ssubtotal()tosum. - Return
sumafter the loop, once, outside it.
The solution in Java
class LineItem {
public String name;
public double price;
public int quantity;
public LineItem(String name, double price, int quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
public double subtotal() {
return price * quantity;
}
}
class Cart {
private List<LineItem> items = new ArrayList<>();
public void add(LineItem item) {
items.add(item);
}
public double total() {
double sum = 0;
for (LineItem item : items) sum += item.subtotal();
return sum;
}
}
class Solution {
public void mainFunction() {
Cart empty = new Cart();
System.out.println("Empty: " + (int)empty.total());
LineItem apple = new LineItem("Apple", 5, 3);
System.out.println("Subtotal: " + (int)apple.subtotal());
Cart cart = new Cart();
cart.add(apple);
cart.add(new LineItem("Bread", 20, 3));
System.out.println("Total: " + (int)cart.total());
cart.add(new LineItem("Milk", 10, 2));
System.out.println("Total: " + (int)cart.total());
}
}
Java details worth knowing:
- Imports.
ListandArrayListcome fromjava.util, so a standalone file needsimport java.util.*;. this.name = name;A parameter hides the field of the same name inside the constructor. Withoutthis., the line would assign the parameter to itself and the field would keep its default value,nullfor the name.- Whole numbers as
double.new LineItem("Apple", 5, 3)passes theint5 where adoubleis expected. Java widens it automatically, soprice * quantityis adoubleandtotal()returnsdouble. - The
(int)cast in the driver truncates. It drops the fraction, it doesn't round: a cart holding a single item priced 19.99 with quantity 1 prints19through(int)cart.total(). - The list stores references.
Cartholds the sameLineItemobjects the caller created. If a caller keeps theappleobject, adds it to a cart and later setsapple.quantity = 10, the cart's nexttotal()sees the change: with an apple at price 5, the total was15.0and becomes50.0. - Private list, public fields.
itemsis private, so the only way to put rows into the cart isadd. The fields ofLineItemare public here, which keeps the lesson short.
Complexity
add is amortized O(1), and subtotal is O(1). total() visits each row once, so it is O(n) for n rows, every time it is called. The cart stores n references, so its space is O(n).
Edge cases and common mistakes
- The empty cart. The loop doesn't run, and
sumis still 0, so the total is0. - Declaring
suminside the loop. It would restart at 0 for every row, and the return line outside the loop couldn't see it. - Returning inside the loop. A
return sum;in the loop body would stop after the first row. - Storing the total in a field. A cached total would be wrong after the next
addunless every change updated it. Computing it on demand avoids that. - Decimal prices. Binary
doublecan't store most decimal fractions exactly, so totals built from prices like 0.1 can carry tiny rounding errors. For money in a larger program, whole cents orBigDecimalare safer. The lesson's driver uses whole numbers.
