classDiagram
class Account {
+String email
+String role
+login()
}
class Admin {
+suspend(Account)
}
class Member {
+listOrders()
}
Account <|-- Admin
Account <|-- Member
Composition and cardinality
An order owns its line items. The quoted numbers are the multiplicity on each end of the association.
classDiagram
class Order {
+String id
+int total
+addItem(sku)
}
class Line {
+int quantity
+int price
}
class Product {
+String sku
+String name
}
Order "1" *-- "1..*" Line : contains
Line "*" --> "1" Product : refers to
Interface and implementation
A dashed triangle is realization: the class implements the interface. The stereotype marks the interface.
classDiagram
class Repository {
<<interface>>
+find(id)
+save(entity)
}
class SqlRepository {
-Connection db
+find(id)
+save(entity)
}
Repository <|.. SqlRepository
What is a Class Diagram?
A Mermaid class diagram is a UML class diagram written as text. A class block lists attributes and methods. Visibility markers are + public, - private, and # protected. Relationships are arrows: <|-- for inheritance, *-- for composition, o-- for aggregation, and --> for a plain association. Cardinality, when you need it, sits in quotes on the arrow. Use a class diagram to agree on the object model before writing the code, or to explain a module to someone reading it later.
When to use it
Use a class diagram for domain models, service interfaces, and inheritance hierarchies. Use an ER diagram when the boxes are database tables with keys. Use a sequence diagram when you care about the order of method calls rather than the types that own them.
Write Parent <|-- Child. The arrowhead is a hollow triangle on the parent, which matches UML generalization. One parent can have several children, each on its own line.
Inside the class body, write one member per line. Prefix an attribute with a type, such as +String email. Write a method with parentheses, such as +login(). Use + , - , or # for public, private, and protected.
A class diagram models software types, methods, and inheritance. An ER diagram models database tables, columns, and keys using crow's foot notation. Use the class diagram for the object model and the ER diagram for the schema.
Mark the interface with the <<interface>> stereotype and connect it with a dashed triangle: Repository <|.. SqlRepository. The dashed line is realization, not inheritance.
Put the multiplicity in quotes on the relationship. Order "1" *-- "1..*" Line means one order contains one or more lines. Use *-- when the child belongs to the parent, and --> when it is only a reference.
Ready to create your own class diagram?
Open the editor with this example pre-loaded and start customizing.