How do you read a UML class diagram, and what do the symbols tell you about the Java code to write?
A class diagram is a picture of a type and the relationships between types. Each class is drawn as a box with three compartments: the name on top, the attributes in the middle and the operations at the bottom. A plus sign in front of a member means public, a minus means private and a hash means protected. The operations list usually shows the return type and the parameter types, which is usually enough to write the signatures.
public class Main {
public static void main(String[] args) {
Order order = new Order("Ada");
order.add(new OrderLine("Book", 12.0));
System.out.println(order.total());
}
}
class Order {
private final String customer;
private final java.util.List<OrderLine> lines = new java.util.ArrayList<>();
Order(String customer) { this.customer = customer; }
void add(OrderLine line) { lines.add(line); }
double total() {
double sum = 0;
for (OrderLine l : lines) { sum += l.amount(); }
return sum;
}
}
class OrderLine {
private final String product;
private final double amount;
OrderLine(String product, double amount) { this.product = product; this.amount = amount; }
double amount() { return amount; }
}The code above is what the diagram for an order model looks like in practice. The order holds a customer name and a list of order lines, and the line holds a product description and an amount. The association between order and order line is one to many, shown on a diagram with a multiplicity at each end, and that is what the collection field represents in code.
The association types map onto code in a predictable way. A plain association becomes a field holding a reference to the other type. Aggregation and composition are both represented by a field, and the difference is expressed through ownership: a composition has no way to attach an externally created part, so the whole creates it internally. An open triangle arrowhead on a line denotes generalisation, which is inheritance in code. A dashed line usually means a dependency, which in code is a collaborator used temporarily rather than stored.
The practical warning is that a diagram is a snapshot, not the code. Multiplicities and ownership are the parts most often wrong, because the diagram is rarely updated when the relationship changes. Treat it as a conversation starter and confirm the details in the code.