Start learning free

LESSON 664 OF 671 · PROJECTS: OBJECT-ORIENTED

Shopping Cart in Java: LineItem and Cart Classes

Practice Read the full explanation

A shop keeps its orders in a cart. Build two classes that work together: a LineItem is one row of the cart (a product, its price and how many were bought), and a Cart holds many rows and adds them up. The cart has line items (composition), it is not one.

LineItem

  • Public fields String name, double price, int quantity.
  • LineItem(String name, double price, int quantity) stores the three values with this..
  • double subtotal() returns price * quantity.

Cart

  • It keeps its items in private List<LineItem> items = new ArrayList<>().
  • void add(LineItem item) appends the item to the list.
  • double total() returns the sum of the subtotals of all items: start double sum = 0, loop over the items, return sum.

Rules:

  • The total is worked out every time it is asked for, from the items in the cart at that moment. Adding an item later changes the next total.
  • An empty cart has a total of 0.
  • An item with price 5 and quantity 3 has a subtotal of 15.
  • Prices in the driver are whole numbers.

Prices are double, so the driver casts the result with (int) to print 75 and not 75.0. The driver lives in Solution.mainFunction().

The driver (already in the starter code, don't change it) creates an empty cart, checks one subtotal, then fills a cart and prints the total twice:

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());
    }
}

Expected output:

Empty: 0
Subtotal: 15
Total: 75
Total: 95

Write LineItem (fields, constructor, subtotal) first, then Cart with its List.

for (LineItem item : items) sum += item.subtotal();

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());
    }
}

STEP 1 OF 18
    Ctrl + Enter to check

    JAVA · PROJECTS: OBJECT-ORIENTED

    Shopping Cart in Java, explained

    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.

    • LineItem has public fields String name, double price and int quantity, a constructor LineItem(String name, double price, int quantity) and a method double subtotal() that returns price * quantity.
    • Cart keeps a private List<LineItem> items, has void add(LineItem item) to append a row, and double 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

    1. Declare LineItem first, because Cart uses it.
    2. Add the three public fields: name (a String), price (a double) and quantity (an int). A quantity is always whole, and a price may not be.
    3. Write the constructor. It has the class's name and no return type, and takes the three values.
    4. Store each parameter in its field with this.. The parameters share the fields' names, so this.name means the field and plain name means the parameter.
    5. Add subtotal(), returning a double: the row's price times its quantity. Both are fields of the same object, so no this. is needed.
    6. Declare Cart below LineItem.
    7. Add the private items list, a List<LineItem> that starts as an empty ArrayList.
    8. Write add, a public void method that appends the item with items.add(item).
    9. Write total(). Start a double sum at 0, so an empty cart gives 0.
    10. Loop over the rows with the colon form of for, and add each row's subtotal() to sum.
    11. Return sum after 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. List and ArrayList come from java.util, so a standalone file needs import java.util.*;.
    • this.name = name; A parameter hides the field of the same name inside the constructor. Without this., the line would assign the parameter to itself and the field would keep its default value, null for the name.
    • Whole numbers as double. new LineItem("Apple", 5, 3) passes the int 5 where a double is expected. Java widens it automatically, so price * quantity is a double and total() returns double.
    • 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 prints 19 through (int)cart.total().
    • The list stores references. Cart holds the same LineItem objects the caller created. If a caller keeps the apple object, adds it to a cart and later sets apple.quantity = 10, the cart's next total() sees the change: with an apple at price 5, the total was 15.0 and becomes 50.0.
    • Private list, public fields. items is private, so the only way to put rows into the cart is add. The fields of LineItem are 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 sum is still 0, so the total is 0.
    • Declaring sum inside 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 add unless every change updated it. Computing it on demand avoids that.
    • Decimal prices. Binary double can'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 or BigDecimal are safer. The lesson's driver uses whole numbers.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free