labs / tiddlers / content / labs / lab02 /

Now we need the Invoice class.

  1. Create a new class named Invoice.

  2. Add the four fields for this class to the class. If you are wondering where the fourth field is coming from, you have forgotten that association relationships are also fields --- there is a field for the items association that is a collection.

  3. Add getters and setters.

  4. Add the addItem and removeItem methods --- they should add/remove the passed InvoiceItem parameter to/from the items collection.

    Don't forget to initialise the items field unless you enjoy debugging null-pointer exceptions. You should remember from INFO201 that HashSet should be your default collection rather than ArrayList.

  5. Add the getTotal method --- it should return the sum of all of the item totals for the items in the items collection.

    You can do this quickly using the following code:

    return -> item.getItemTotal()).sum();

    This is using a combination of lambda expressions and sequence streams (both of which have been in Java since Java 8) to iterate through all of the items, calling the getItemTotal on each, and summing the result to get the invoice total. We could have done this with a loop, but learning new techniques is how we gain experience. The old adage that Java is a verbose language hasn't been true for close to a decade.