Home / Examples / Class Diagram

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.

classDiagram
  class PaymentMethod {
    <<interface>>
    +charge(amount) Receipt
  }
  class CreditCard {
    -string number
    +charge(amount) Receipt
  }
  class PayPal {
    -string email
    +charge(amount) Receipt
  }
  PaymentMethod <|.. CreditCard
  PaymentMethod <|.. PayPal

Composition, aggregation, and cardinality

*-- is composition (line items cannot exist without their order), o-- is aggregation, and quoted values on each side set the cardinality.

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 : references

Generic repository with inheritance

Wrap a type parameter in tildes, such as Repository~T~, to show generics. <|-- draws inheritance.

classDiagram
  class Repository~T~ {
    <<abstract>>
    #Database connection
    +findById(id) T
    +save(T entity) void
  }
  class UserRepository {
    +findByEmail(email) User
  }
  Repository <|-- UserRepository

Class Diagram syntax cheat sheet

SyntaxMeaning
A <|-- BInheritance (B extends A)
A <|.. BRealization (B implements A)
A *-- BComposition
A o-- BAggregation
A --> BAssociation
A ..> BDependency
A "1" --> "*" BCardinality 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~, not List<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

More Mermaid examples

Last updated 2026-11-28.