The idea: a map of the classes and how they know each other

A class diagram is a picture of the code's structure. Each class is a box. Each line between two boxes says how the two classes are tied together: one keeps a field of the other, one extends the other, or one only uses the other for a moment. The diagram does not show what happens when the program runs; a sequence diagram does that.

Left: the Java class Order with private int id, protected String status, String note with no modifier, and three public methods. Right: the matching class box with three compartments: the name Order; the attributes minus id colon int, hash status colon String, tilde note colon String; the operations plus addLine, plus total, plus buy. Arrows join each Java line to its row in the box.
One Java class, one box: name, attributes, operations. The sign in front of each member is its visibility.

The canvas has a small shop with eight classes. Their boxes are there from the start; the lines are not. Pick a relationship and press Show: the Java code that makes it appears at the bottom left, the key piece of code flies to the class that holds it, and the line grows between the two boxes. The panel at the bottom right is the running program, with real objects. Drop removes a reference there, so you can see what each kind of line means for an object's life.

Reading a class box

The box has three compartments: the class name, the attributes (fields) and the operations (methods). UML writes the name first and the type after a colon, the other way round from Java: - id: int for private int id. Method bodies are never shown. Demo 1: a class box, visibility + - # ~.

SignVisibilityJavaWho can use it
+publicpublicevery class
-privateprivateonly the class itself
#protectedprotectedthe class and its subclasses (in Java also its package)
~packageno modifierclasses in the same package

An interface gets the word «interface» above its name, like Shippable. An abstract class gets {abstract} (or its name in italics), like Payment. In the Order box, 3 attributes are private, protected and package, and all 4 operations are public. Private fields and public methods is the usual shape: encapsulation you can see at a glance.

Association, multiplicity and navigability

An association is a field that keeps a reference to another class. Customer has List<Order> orders and Order has Customer customer, so a solid line joins the two boxes. When both sides keep a field, the line has no arrowhead. When only one side does, an open arrowhead points to the class that is known: OrderLine has a Product field, Product has nothing back, so the arrow points to Product. That is navigability. Demo 2: association and multiplicity.

The small numbers at the ends are the multiplicity. Read them across the line: the number next to a class says how many objects of that class one object at the other end is linked to. Next to Order it says 0..*: one customer has any number of orders. Next to Customer it says 1: one order has exactly one customer. The field's type usually tells you: a single field is 1 (or 0..1 if it can be null), a list is 0..*.

MultiplicityMeansTypical Java
1exactly onea field set in the constructor, never null
0..1none or onea field that may be null
0..* (or *)any numberList<T> that may be empty
1..*at least onea list that is never empty (a rule in the code)

Aggregation and composition: who owns the parts

Both are associations between a whole and its parts. The diamond sits at the whole.

  • Aggregation, a hollow diamond: the whole holds parts that were made elsewhere and can be shared. Catalog.add(Product p) takes a product someone else made, and one product can be in many catalogs (0..* at both ends).
  • Composition, a filled diamond: the whole makes its parts and never hands them out. Order.addLine(p) does new OrderLine(p) and keeps it in a private list. A line belongs to exactly one order: the multiplicity next to Order is 1. Demo 3: aggregation vs composition.

The real difference is lifetime. Java has no delete: an object lives while something the program can still reach points at it, and the garbage collector takes the rest. In the objects panel, main() holds c1 and cat. c1.removeOrder(1) drops the only reference to o1. Nothing else points at l1 and l2, because only the order ever had them, so they go with it: 3 objects are collected and 4 of 7 stay alive. The products stay, because the catalog still holds them. Demo 6: drop the Order, its lines go too.

Two panels of objects. Before: main holds c1 and cat; c1 points to o1; o1 points to l1 and l2; l1 points to p1, l2 to p2; cat points to p1 and p2. All 7 alive. After c1.removeOrder(1): o1, l1 and l2 are red with a cross: collected; c1, cat, p1 and p2 are still green. 4 of 7 alive.
Drop the whole of a composition and its parts go too. Parts of an aggregation stay as long as something else holds them.

cat = null drops the catalog instead. Only cat is collected (6 of 7 alive): p1 and p2 are still reached through the order's lines. That is what the hollow diamond allows: the parts do not depend on the whole. Demo 7: drop the Catalog, products live on. If you drop both, the products go too, because nothing holds them any more. A Java object never dies "with" its whole by magic; composition is a promise in the design that no one else keeps a reference to the part.

Generalization and realization

Generalization is extends: a solid line with a hollow triangle at the parent. CardPayment extends Payment, so a card payment is a payment and gets amount from it. Realization is implements: the same triangle on a dashed line. Order implements Shippable, so Order must have weight(). Neither line has multiplicities: they tie classes together, not objects. Demo 4: generalization and realization. Whether to use inheritance at all is a design question; Inheritance vs Composition plays it out.

Dependency: used, not kept

A dependency is a dashed line with an open arrow. Order.buy(Payment p) uses a payment that comes in as a parameter and keeps no field of it. If Payment changes, Order may have to change too, but an Order object does not hold a Payment. It is the weakest line. Parameters, local variables and calls to static methods give dependencies. Demo 5: dependency, a parameter not a field.

From a line of Java to the right UML line

To draw a class diagram from code, look at each class and ask a few questions in order. The figure is the same check as a flow.

A decision flow. Does the class extend the other one? Yes: generalization, solid line with hollow triangle. Does it implement it? Yes: realization, dashed line with hollow triangle. Does it keep a field of it? No: dependency, dashed line with open arrow. Yes: did the whole make the part with new and never give it out? Yes: composition, filled diamond. Is the part made elsewhere and shared? Yes: aggregation, hollow diamond. Otherwise: association, solid line.
extends and implements give a triangle; a field gives an association (with a diamond if it is a whole and its parts); only using it gives a dependency.
LineDrawn asJava on the canvas
Associationsolid line, multiplicity at both endsList<Order> orders / Customer customer
Directed associationsolid line, open arrowProduct product in OrderLine only
Aggregationhollow diamond at the wholeList<Product> products + add(Product p)
Compositionfilled diamond at the wholelines.add(new OrderLine(p))
Generalizationsolid line, hollow triangleclass CardPayment extends Payment
Realizationdashed line, hollow triangleclass Order implements Shippable
Dependencydashed line, open arrowvoid buy(Payment p) { p.pay(); }

The whole shop has 7 lines and 8 multiplicity labels: the four associations (plain, directed, aggregation, composition) carry two each, the other three carry none. Demo 8: the whole diagram, 7 lines. Few lines and few boxes with many lines is what low coupling looks like on paper. Design rules such as "depend on an interface, not a class" are easy to check on the diagram: see SOLID.

See also UML state machine and activity diagrams for how one object of a class changes state over its life, and how a process flows across swimlanes.

What the page leaves out

Static members (underlined in UML), default values and constraints in braces such as {ordered}, role names and association names on the lines, association classes, qualified associations, n-ary associations with a diamond in the middle, generic (template) classes, enumerations, nested classes and packages. Object diagrams underline the object names (o1:Order); the panel does not. UML 2 does not define the meaning of aggregation precisely, so teams use it differently, and some leave it out. The objects panel uses plain Java reachability: a real collector runs later and decides itself when to free the memory, see Java garbage collection. State and activity diagrams are on another page.

On the mind map

Open the Software Design mind mapSoftware DesignPrinciples: keep each change localPrinciplesDesign patterns: named fixes for common designsDesign patternsArchitecture: the shape of a whole appArchitectureEnterprise app patterns: logic, SQL, locks, money (PoEAA)Enterprise app patternsGit storage: content named by its hashGit storageGit branches & merging: pointers to commits, then mergeGit branches & mergingTesting: check code in isolationTestingHexagonal architectureHexagonal architecturedomain in the middle, adapters at portsLayered vs Pipes vs EventsLayered vs Pipes vs EventsClosed layers add hops; queues absorb faultsUML Sequence DiagramUML Sequence DiagramTime runs down; one arrow per callUML class diagramA field is a line; diamond = whole and partsState and activity diagramsState and activity diagramsExits inside out, entries outside inVirtual DOM diffingVirtual DOM diffingdiff new tree vs old, patch only changesMVC vs MVVMMVC vs MVVMController routes input; view-model bindsOpen the Software Design mind mapSoftware Designthe shape of a whole appArchitectureHexagonal architectureHexagonal architecturedomain in the middle, adapters at portsLayered vs Pipes vs EventsLayered vs Pipes vs EventsClosed layers add hops; queues absorb faultsUML Sequence DiagramUML Sequence DiagramTime runs down; one arrow per callUML class diagramA field is a line; diamond = whole and partsState and activity diagramsState and activity diagramsExits inside out, entries outside inVirtual DOM diffingVirtual DOM diffingdiff new tree vs old, patch only changesMVC vs MVVMMVC vs MVVMController routes input; view-model binds
This page on the Software Design mind map · 38 pages in 7 branches · open it to see the whole map and test yourself in recall mode.