Skip to content

UML Class Diagrams: Reading and Drawing the Boxes

class box, visibility markers, attribute and method syntax, interface, abstract class, enum, and the three perspectives

Stage 1intro13 min read

Before you write code for a big program, it helps to draw it. A UML class diagram is that drawing. UML stands for Unified Modeling Language, which is just a standard way of drawing software designs so that everyone reads them the same way.

A class diagram shows:

  • the classes, interfaces and enums in the program
  • what each one holds (its attributes, also called fields)
  • what each one can do (its operations, also called methods)
  • how they are connected to each other

You can use a class diagram in two ways:

  • Design first. You draw the classes, talk about them with your team, and then write the code.
  • Code first. You already have the code, and a tool draws the diagram from it. This helps a new person understand the program without reading every file.

Teams usually draw a rough diagram at the start of a project and update it as the project grows. It shows the real-world things the system is about (like Customer and Order), what gets stored, and how the big parts fit together.

Once you can read a class diagram, you can see what parts a system has and how they work together, even if you have not read the code.

This note is about the boxes: what goes inside a class box, how to show who can access what, how interfaces, abstract classes and enums look, and how much detail to draw for different people. The lines between the boxes are covered in Class Relationships. Section 9 below has a short summary of them.


1. The class box

A class is drawn as a rectangle with three parts, one on top of the other:

PartWhat goes in it
TopThe name of the class
MiddleThe attributes (the data it keeps)
BottomThe operations (the methods it has)

Here is a Person class drawn by hand:

+---------------------------+
|          Person           |   <- name
+---------------------------+
| - name: String            |   <- attributes
| + age: int = 21           |
+---------------------------+
| + getName(): String       |   <- operations
| - isAdult(age: int): bool |
+---------------------------+

And here is the same box in Mermaid. Mermaid is the tool this website uses to draw diagrams from text, so you will see it in every diagram in this note:

Loading diagram…

Every line inside the box has three things: a small symbol at the start (the next section explains it), a name, and a type. For an attribute, the type is the kind of data it holds, such as String. For a method, the brackets hold the inputs, and the type after them is what the method gives back.

You do not have to show all three parts. If a class has no attributes, leave that part out. You can even draw a box with only the name. Section 8 explains when to do that.

A small difference to know about: real UML writes the name first and the type after a colon, like age: int. Mermaid writes the type first, like int age. They mean the same thing. The tables in this note show the real UML way, and the Mermaid diagrams use the Mermaid way.


2. Visibility markers

The first character on every attribute and method says who is allowed to use it. This is called visibility.

MarkerNameWho can use itJava word
+PublicAny other classpublic
-PrivateOnly the class itselfprivate
#ProtectedThe class itself and the classes that extend itprotected
~PackageClasses in the same package(nothing, the default)

These markers show encapsulation. This means the data stays hidden inside the class, and other classes can reach it only through methods. The usual good pattern is private attributes (-) with public methods (+).

Loading diagram…

How to read this: balance is private, so no outside class can change it directly. They have to call deposit(), which can check the amount first. If you see a + in front of an attribute, ask why that data is open to everyone.


3. How to write an attribute

The pattern is:

visibility name: Type [multiplicity] = defaultValue
PartWhat it meansMust you write it?
visibility+, -, # or ~Yes
nameThe name of the attributeYes
TypeThe kind of data, like int or StringYes
multiplicityHow many values it holds, like 0..1 or 1..*No
defaultValueThe value it starts withNo

Multiplicity is just a count. 0..1 means "none or one" (the value is optional). 1..* means "one or many". 0..* means "any number, even none".

Here is the same attribute in Java and in UML:

JavaUML
public int age = 21;+ age: int = 21
private String name;- name: String
private List<String> phones;- phones: String [0..*]
private String nickname; (may be null)- nickname: String [0..1]
protected static int count = 0;# count: int = 0 (underlined)

Notice the last row. A static member belongs to the class itself, so all objects share one copy. In UML you underline the whole line, which plain text cannot show here. In Mermaid you add a $ at the end instead. The # is the protected marker, not a static marker.


4. How to write a method

The pattern is:

visibility name(parameterName: Type, ...): ReturnType
PartWhat it means
visibility+, -, # or ~
nameThe name of the method
parameterNameThe name of each input
TypeThe type of each input
ReturnTypeWhat the method gives back (void if nothing)

Take this Java class:

class Person {
    private boolean isAdult(int age) {
        return age >= 18;
    }
}

The method in UML is:

- isAdult(age: int): boolean

Read it from left to right: private, called isAdult, takes an int called age, and gives back a boolean.

More examples:

JavaUML
public void deposit(double amount)+ deposit(amount: double): void
public String getName()+ getName(): String
public Order place(Cart c, String coupon)+ place(c: Cart, coupon: String): Order
protected abstract void refund()# refund(): void (written in italics)

A constructor is shown with the class name and no return type. Some people add the label <<constructor>>. Most diagrams leave constructors out so the box stays small.


5. Interface

An interface is a list of promises. It says what a class must be able to do, but not how it does it. For example, Payable says "I can calculate pay". It does not say how.

An interface box has two parts:

  • The top part has the label <<interface>> above the name. A label in double angle brackets is called a stereotype. It tells you what kind of box this is.
  • The bottom part lists the method signatures.

There is no attribute part, because an interface does not store data. The only time you add one is when the interface has constants (fixed values).

interface Payable {
    double calculatePay();
}
Loading diagram…

The dashed line with a hollow triangle means "implements". Employee signs up to the promise, so it must write its own calculatePay(). The triangle always points at the interface.


6. Abstract class

An abstract class is a half-finished class. You cannot create an object from it with new. It can have normal methods that already work, and abstract methods that have no body yet. Child classes must write the body of each abstract method.

It is drawn like a normal class, with two changes:

  • The label <<abstract>> goes above the name.
  • The class name is written in italics. Abstract methods are in italics too.
abstract class Animal {
    protected String name;
    public abstract void makeSound();
    public void sleep() { /* the same for all animals */ }
}
Loading diagram…

In Mermaid, a * after the brackets marks an abstract method. Dog is a normal class, so it has to give makeSound() a real body. It gets name and sleep() from Animal for free. The solid line with a hollow triangle means "inherits from" (a Dog is an Animal).

Here is how to tell the three kinds of box apart:

You seeWhat it is
<<interface>>Only promises. No data and no method bodies.
<<abstract>>A half-finished class. You cannot make an object from it.
No labelA normal class you can use with new.

7. Enumeration

An enum is a type that can only be one value from a small, fixed list. Each value is called a literal. A good example is the status of an order: it can be placed, packed, shipped, and so on, and nothing else.

An enum box has the label <<enumeration>> above the name, and the literals listed in the part below.

enum OrderStatus {
    PLACED, PACKED, SHIPPED, DELIVERED, CANCELLED
}
Loading diagram…

Order has a field of type OrderStatus, so an arrow goes from Order to OrderStatus. The literals have no + or - in front, because they are always public.


8. Three levels of detail

You can draw the same system with more or less detail, depending on who will read it. UML calls these levels perspectives.

Many beginners draw every field and method every time. That is a mistake. A business person cannot read it, and even a developer gets lost. Pick the level that fits the reader.

PerspectiveWho reads itWhy you draw itWhat you show
ConceptualBusiness analysts, domain expertsTo agree on what things existOnly class names and how they relate
SpecificationArchitects, designersTo decide who is responsible for whatInterfaces, abstract classes, important public methods
ImplementationDevelopersTo guide the code that will be writtenEvery attribute and method, with visibility and types

Here is the same online shop at all three levels.

Conceptual. Only the real-world things, and the words the business uses to link them, such as "places". No attributes and no methods.

Loading diagram…

Specification. What each part promises to do. You show interfaces and the main public methods, and leave out private details.

Loading diagram…

Implementation. Everything a developer needs in order to write the class.

Loading diagram…

At this level, you draw every kind of line: association, aggregation, composition, inheritance, realization and dependency.

A good habit: start with the conceptual view, and add detail only for the part you are explaining right now. In an interview, a specification-level diagram with a few key methods usually works better than one full of fields.


9. The lines between boxes: a short summary

Each kind of relationship has its own line and its own arrow end. The full explanation, with Java code and database tables, is in Class Relationships.

RelationshipWhat it meansHow it is drawnExample
AssociationOne class knows about or uses anotherA plain lineTeacher and Student
AggregationA whole has parts, and the parts can live without itA hollow diamond on the wholeA Department has Professors
CompositionA whole owns its parts, and they die with itA filled diamond on the wholeA House has Rooms
InheritanceOne class is a kind of anotherA solid line with a hollow triangle on the parentA Dog is an Animal
RealizationA class implements an interfaceA dashed line with a hollow triangle on the interfaceA Circle implements Shape
DependencyOne class uses another only for a short timeA dashed line with an open arrowOrderService uses PaymentService
Loading diagram…

10. How to read a diagram, step by step

When you get a new diagram, do these things in order:

  1. Look at the labels first. <<interface>>, <<abstract>> and <<enumeration>> tell you which boxes are promises and which are real classes.
  2. Follow the hollow triangles. They point from a child to its parent or interface. This shows you the family tree of the design.
  3. Find the diamonds. A diamond sits on the whole and means "this is made of those parts". A filled diamond means the whole owns the parts.
  4. Read the numbers on the lines. 1, 0..1 and * tell you how many objects are on each side. For example, one Order has 1..* items.
  5. Check the visibility. Private attributes (-) and public methods (+) are normal. A public attribute is worth a question.
  6. Look at the dashed arrows. They are short-term uses. If many dashed arrows point at one class, many classes depend on it, so changing it is risky.

11. Common mistakes

MistakeWhy it is a problem
Showing every getter and setterThe box gets long and the important methods get lost
Using the implementation level for a business readerThey cannot follow it and stop trusting the diagram
Putting the diamond on the wrong endThe diamond always goes on the whole, not on the part
Mixing up filled and hollow diamondsIt changes the meaning from "owns" to "just borrows"
Forgetting <<interface>> or <<abstract>>Readers think it is a normal class and miss that it is a contract
Leaving out the numbers on linesOne-to-one and one-to-many look the same
Pointing the triangle at the childThe triangle always points at the parent or the interface
Drawing the whole system in one diagramSplit it by area and draw only the classes the story needs


Interview questions

"What is a UML class diagram and what is it used for?"

It is a drawing of the structure of a system. It shows the classes, interfaces and enums, what attributes and methods each one has, and how they are connected. Teams use it to plan a design before coding, to explain a system to new people, and to understand existing code.

"What are the parts of a class box?"

There are three parts. The top has the class name, the middle has the attributes, and the bottom has the methods. Each line in the middle and bottom has a visibility symbol, a name and a type.

"What do the visibility markers mean?"

+ is public, - is private, # is protected and ~ is package. They show encapsulation. Private data with public methods is the usual pattern.

"How do you write an attribute and a method in UML?"

An attribute is visibility name: Type [multiplicity] = default, for example + age: int = 21. A method is visibility name(param: Type): ReturnType, for example - isAdult(age: int): boolean.

"How is an interface different from an abstract class in a diagram?"

An interface has the label <<interface>>, lists only methods, and has no attributes. A class connects to it with a dashed line and a hollow triangle. An abstract class has the label <<abstract>> and an italic name. It can have attributes and methods with bodies. A child class connects to it with a solid line and a hollow triangle.

"How is an enum shown?"

It is a box with the label <<enumeration>> above the name, and the values listed below. Classes that use the enum have an arrow pointing to it.

"What are the three perspectives of a class diagram?"

Conceptual shows only the main things and how the business relates them. It is for analysts and domain experts. Specification shows interfaces, abstract classes and the key public methods. It is for architects and designers. Implementation shows every attribute and method with visibility and types. It is for developers.

"What is the difference between aggregation and composition?"

Both mean a whole has parts. In aggregation the parts can live without the whole, like professors in a department. It uses a hollow diamond. In composition the parts die with the whole, like rooms in a house. It uses a filled diamond. The diamond is always on the whole's side.

"Which arrow end means inheritance and which means realization?"

Both use a hollow triangle that points at the parent. Inheritance uses a solid line. Realization, which is a class implementing an interface, uses a dashed line.

"How much detail should you put in a class diagram?"

Only as much as the reader needs. For business people, show names and relationships. For a design discussion, show interfaces and the key public methods. Show every field and method only when developers are about to write the code.

In this topic

Done with this topic?

How well do you know it?

PreviousOOP Notes
Practise 10 questions