Java
OOP model
Set up the class hierarchy and interfaces.
OrderBook manages the collection
Once you have a single Order instance, you need to collect them in a list. The OrderBook class does this: it holds a List<Order> named orders and adds new orders through an add method. The listAll method prints each order with forEach.
The line List<Order> orders = new ArrayList<>(); gives every new OrderBook instance an empty list. The add method does one thing in a single line: orders.add(o);. listAll walks all orders with orders.forEach(o -> System.out.println(...)).
listAll with forEach
The listAll method prints all orders with orders.forEach(o -> System.out.println(o.id + " " + o.customer + " " + o.amount));. forEach expects a Consumer; the lambda defines a print action for each order.
This is shorter than a classic for-each loop. It walks each order and prints its id, customer and amount fields on one line. The output format is deterministic: lines appear in insertion order.
Exercise Write the OrderBook class and listAll method
The Order class from above is ready. Now define class OrderBook with a List<Order> orders field initialized to an empty ArrayList, a void add(Order o) method that calls orders.add(o);, and a void listAll() method that calls orders.forEach(o -> System.out.println(o.id + " " + o.customer + " " + o.amount));. In main, create an OrderBook book = new OrderBook();, add two orders and call book.listAll();.
Show example solution
class Order {
String id;
String customer;
int amount;
Order(String id, String customer, int amount) {
this.id = id;
this.customer = customer;
this.amount = amount;
}
}
class OrderBook {
List<Order> orders = new ArrayList<>();
void add(Order o) { orders.add(o); }
void listAll() {
orders.forEach(o -> System.out.println(o.id + " " + o.customer + " " + o.amount));
}
}
public class Main {
public static void main(String[] args) {
OrderBook book = new OrderBook();
book.add(new Order("1", "Ayşe", 50));
book.add(new Order("2", "Alex", 150));
book.listAll();
}
}
Test yourself
-
Complete the add method
void add(Order o) { orders.____(o); }
Show answer
void add(Order o) { orders.add(o); }
-
What relation is there between OrderBook and Order?
- Inheritance
- Dependency
- Composition
- Abstraction
Show answer
Composition — OrderBook contains an Order list; this is composition.
-
Match the OrderBook methods
- add(o)
- Appends an order
- listAll()
- Prints all orders
- orders
- List<Order> field
- forEach
- Method used by listAll
Next lesson: Stream layer