Mermaid Class Diagram Examples
Class diagrams describe the structure of code: classes, their fields and methods, and how they relate. They are useful for domain models, design reviews, and onboarding docs.
A class diagram starts with classDiagram. Members use + (public), - (private), # (protected), and ~ (package) visibility markers.
Interface with two implementations
<<interface>> annotates a class, and <|.. draws a realization (dashed arrow) from each implementation to the interface.
Rendering preview…
classDiagram
class PaymentMethod {
<<interface>>
+charge(amount) Receipt
}
class CreditCard {
-string number
+charge(amount) Receipt
}
class PayPal {
-string email
+charge(amount) Receipt
}
PaymentMethod <|.. CreditCard
PaymentMethod <|.. PayPalComposition, aggregation, and cardinality
*-- is composition (line items cannot exist without their order), o-- is aggregation, and quoted values on each side set the cardinality.
Rendering preview…
classDiagram
class Order {
+UUID id
+total() Money
}
class LineItem {
+int quantity
}
class Customer {
+string email
}
class Product {
+string sku
}
Order "1" *-- "1..*" LineItem : contains
Order "*" o-- "1" Customer : placed by
LineItem --> Product : referencesGeneric repository with inheritance
Wrap a type parameter in tildes, such as Repository~T~, to show generics. <|-- draws inheritance.
Rendering preview…
classDiagram
class Repository~T~ {
<<abstract>>
#Database connection
+findById(id) T
+save(T entity) void
}
class UserRepository {
+findByEmail(email) User
}
Repository <|-- UserRepositoryClass Diagram syntax cheat sheet
| Syntax | Meaning |
|---|---|
A <|-- B | Inheritance (B extends A) |
A <|.. B | Realization (B implements A) |
A *-- B | Composition |
A o-- B | Aggregation |
A --> B | Association |
A ..> B | Dependency |
A "1" --> "*" B | Cardinality on each side |
<<interface>> | Annotation inside a class block |
+ - # ~ | Public, private, protected, package |
Common class diagram mistakes
- Generic syntax uses tildes, not angle brackets:
List~string~, notList<string>. - Method return types go after the parentheses:
+total() Money. - A class that only appears in a relationship still renders, but it has no members until you add a
class Name { }block.
Class Diagram FAQ
How do I mark a method as abstract or static?
Add
* after the method for abstract (+draw()*) or $ for static (+create()$).Can I change the layout direction?
Yes. Add
direction LR on the line after classDiagram.Keep going
- Mermaid vs PlantUML for UML diagrams
- Open the free Mermaid editor to write your own diagram with live preview.
More Mermaid examples
- Mermaid flowchart examples
- Mermaid sequence diagram examples
- Mermaid er diagram examples
- Mermaid state diagram examples
- Mermaid gantt chart examples
- Mermaid pie chart examples
- Mermaid mindmap examples
Last updated 2026-11-28.