Example class diagram code
This is the Mermaid source loaded in the editor above. Copy it into a Markdown file inside a ```mermaid block and GitHub, GitLab, Notion or Obsidian will render it.
classDiagram
direction LR
class Animal {
<<abstract>>
+String name
+int age
+makeSound()* void
+isAdult() bool
}
class Dog {
+String breed
+fetch() void
}
class Cat {
-int lives
+purr() void
}
class Owner {
+String name
+adopt(Animal a) void
}
Animal <|-- Dog
Animal <|-- Cat
Owner "1" --> "0..*" Animal : ownsClass diagram syntax cheat sheet
| Syntax | What it does |
|---|---|
| classDiagram | Start a UML class diagram. |
| class Name { +field; +method() } | Declare a class with members. Visibility: + public, - private, # protected, ~ package. |
| method()* / field$ | Trailing * marks abstract, $ marks static. |
| <<interface>> | Annotation inside a class: interface, abstract, enumeration, service. |
| A <|-- B | Inheritance (B extends A). *-- composition, o-- aggregation, --> association, ..> dependency, ..|> realization. |
| A "1" --> "*" B : label | Relationship with cardinality on each end and a label. |
| direction LR | Lay the diagram out left to right. |
How to make a Mermaid class diagram
- 1Start the code with classDiagram.
- 2Define classes with members inside braces.
- 3Mark visibility with +, -, # or ~.
- 4Add relationships such as Animal <|-- Dog.
- 5Export as SVG or PNG, or copy a share link.
Classes and members
Write class Order { +String id +List~Item~ items +total() Decimal } with one member per line inside the braces. Members with parentheses are methods, and the type after the parentheses is the return type.
Prefix members with + for public, - for private, # for protected and ~ for package or internal. Generics use tildes, as in List~Item~, because angle brackets are reserved.
Relationship arrows
<|-- is inheritance, *-- composition, o-- aggregation, --> association, ..> dependency and ..|> realization (implementing an interface). Add a label after a colon: Customer --> Order : places.
Put multiplicity in quotes on either side: Customer "1" --> "*" Order.
Annotations
Mark special classes with <<interface>>, <<abstract>>, <<enumeration>> or <<service>>, either inside the class body or as <<interface>> Shape on its own line.
Keep diagrams focused: show the classes relevant to one feature rather than the whole codebase.