Class diagram
A class diagram is the main building block of object-oriented modeling. It is used for general conceptual modeling of the structure of an application, as well as for detailed modeling to translate models into programming code. Class diagrams can also be used for data modeling. The classes in a class diagram represent both the main elements and interactions in an application, as well as the classes that need to be programmed.
Copy
Embed
---
title: Animal example
---
classDiagram
note "From Duck till Zebra"
Animal <|-- Duck
note for Duck "can fly
can swim
can dive
can help in debugging"
Animal <|-- Fish
Animal <|-- Zebra
Animal : +int age
Animal : +String gender
Animal: +isMammal()
Animal: +mate()
class Duck{
+String beakColor
+swim()
+quack()
}
class Fish{
-int sizeInFeet
-canEat()
}
class Zebra{
+bool is_wild
+run()
}
Syntax
Class
UML provides mechanisms to represent class members, such as attributes and methods, and their additional information. A single instance of a class contains three parts:
- The top part contains the name of the class. It is printed in bold and centered, and the first letter is capitalized. It may also contain optional annotation text describing the nature of the class.
- The middle part contains the attributes of the class. They are left-aligned and the first letter is lowercase.
- The bottom part contains the operations the class can perform. They are also left-aligned and the first letter is lowercase.
Copy
Embed
---
title: Bank example
---
classDiagram
class BankAccount
BankAccount : +String owner
BankAccount : +Bigdecimal balance
BankAccount : +deposit(amount)
BankAccount : +withdrawal(amount)
Defining a class
There are two ways to define a class
- Explicitly using the class syntax (such as class Animal), which defines the Animal class.
- Through a relationship, which defines two classes and the relationship between them at the same time (such as Vehicle <|-- Car).
Copy
Embed
classDiagram
class Animal
Vehicle <|-- Car
Naming convention: a class name can consist only of alphanumeric characters (including unicode), underscores (_), and dashes (-).
Class label
If you need to provide a label for a class, you can use the following syntax:
Copy
Embed
classDiagram
class Animal["Animal with a label"]
class Car["Car with *! symbols"]
Animal --> Car
You can also use backticks (``) to escape special characters in a label:
Copy
Embed
classDiagram
class `Animal Class!`
class `Car Class`
`Animal Class!` --> `Car Class`
Defining members of a class
UML provides mechanisms to represent class members (such as attributes and methods) and additional information about them.
Mermaid distinguishes attributes from functions or methods based on the presence of parentheses (). Those with () are treated as functions or methods, and the rest are treated as attributes.
There are two ways to define members of a class; regardless of which syntax is used to define the members, the output is the same. The two different ways are:
1. Associate a class member using a colon (:) followed by the member name, which is useful for defining one member at a time. For example:
Copy
Embed
classDiagram
class BankAccount
BankAccount : +String owner
BankAccount : +BigDecimal balance
BankAccount : +deposit(amount)
BankAccount : +withdrawal(amount)
2. Associate class members using braces {}, where the members are grouped inside the braces. Suitable for defining multiple members at once. For example:
Copy
Embed
classDiagram
class BankAccount{
+String owner
+BigDecimal balance
+deposit(amount)
+withdrawal(amount)
}
Return type
You can specify the data type to be returned at the end of a method or function definition. Note: there must be a space between the final ')' and the return type. An example:
Copy
Embed
classDiagram
class BankAccount{
+String owner
+BigDecimal balance
+deposit(amount) bool
+withdrawal(amount) int
}
Generic types
Generic types can be represented as part of a class definition, and can also be used for class members or return types. To represent an item as a generic type, enclose the type in tildes (~). Nested type declarations are supported, such as List<List<int>>, but generic types containing commas, such as List<List<K, V>>, are not currently supported.
Copy
Embed
classDiagram
class Square~Shape~{
int id
List~int~ position
setPoints(List~int~ points)
getPoints() List~int~
}
Square : -List~string~ messages
Square : +setMessages(List~string~ messages)
Square : +getMessages() List~string~
Square : +getDistanceMatrix() List~List~int~~
Visibility
To describe the visibility of an attribute or method/function, an optional symbol can be used before the member name:
- + Public
- - Private
- # Protected
- ~ Internal
Defining relationships
A relationship is a general term covering the specific types of logical connections found on class and object diagrams.
Copy
Embed
[classA][Arrow][ClassB]
UML为类定义了八种不同类型的关系:
| Type | Description |
|---|---|
| <|-- | Inheritance |
| *-- | Composition |
| o-- | Aggregation |
| --> | Association |
| -- | Link (solid) |
| ..> | Dependency |
| ..|> | Realization |
| .. | Link (dashed) |
Copy
Embed
classDiagram
classA <|-- classB
classC *-- classD
classE o-- classF
classG <-- classH
classI -- classJ
classK <.. classL
classM <|.. classN
classO .. classP
We can use a label to describe the nature of the relationship between two classes. In addition, the arrow can also be used in reverse:
Copy
Embed
classDiagram
classA --|> classB : Inheritance
classC --* classD : Composition
classE --o classF : Aggregation
classG --> classH : Association
classI -- classJ : Link(Solid)
classK ..> classL : Dependency
classM ..|> classN : Realization
classO .. classP : Link(Dashed)
Relationship label
Label text can be added to a relationship:
Copy
Embed
[classA][Arrow][ClassB]:LabelText
Copy
Embed
classDiagram
classA <|-- classB : implements
classC *-- classD : composition
classE o-- classF : aggregation
Bidirectional relationship
A bidirectional relationship can logically represent an N:M association:
Copy
Embed
classDiagram
Animal <|--|> Zebra
语法如下:
Copy
Embed
[Relation Type][Link][Relation Type]
其中 Relation Type 是以下之一:
| Type | Description |
|---|---|
| <| | Inheritance |
| * | Composition |
| o | Aggregation |
| > | Association |
| < | Association |
| |> | Realization |
Link is one of the following:
| Type | Description |
|---|---|
| -- | Solid line |
| .. | Dashed line |
Lollipop interface
A class can also be given a special relationship type that defines a lollipop interface for the class. The lollipop interface is defined using the following syntax:
- bar ()-- foo
- foo --() bar
The interface with a lollipop (bar) connects to the class (foo).
Note: every defined interface is unique, so that it is not shared between classes and multiple connections pointing to it are not allowed.
Copy
Embed
classDiagram
bar ()-- foo
Copy
Embed
classDiagram
class Class01 {
int amount
draw()
}
Class01 --() bar
Class02 --() bar
foo ()-- Class01
Defining a namespace
A namespace groups classes.
Copy
Embed
classDiagram
namespace BaseShapes {
class Triangle
class Rectangle {
double width
double height
}
}
Cardinality/multiplicity of relationships
Multiplicity or cardinality in a class diagram represents the number of instances of one class that can be linked to an instance of another class. For example, every company will have one or more employees, never zero, and every employee currently works for zero or one company.
The multiplicity notation is placed near the end of the association.
The different cardinality options are:
- 1 Only one
- 0..1 Zero or one
- 1..* One or more
- * Zero or one or more
- n n (where n>1)
- 0..n Zero to n (where n>1)
- 1..n One to n (where n>1)
Cardinality can be easily defined by enclosing the text option in double quotes "" before or after a given arrow. For example:
Copy
Embed
[classA] "cardinality1" [Arrow] "cardinality2" [ClassB]:LabelText
Copy
Embed
classDiagram
Customer "1" --> "*" Ticket
Student "1" --> "1..*" Course
Galaxy --> "many" Star : Contains
Annotations for classes
A class can be annotated with a marker to provide additional metadata about the class. This can more clearly indicate the nature of the class. Some common annotations include:
- <<Interface>> represents an interface class
- <<Abstract>> represents an abstract class
- <<Service>> represents a service class
- <<Enumeration>> represents an enumeration
Annotations are defined between << at the beginning and >> at the end. There are three ways to add annotations to a class, and all three produce the same output:
- Inline with the class definition
Copy
Embed
classDiagram
class Shape <<interface>>
On a separate line after the class definition:
Copy
Embed
classDiagram
class Shape
<<interface>> Shape
Shape : noOfVertices
Shape : draw()
- In a nested structure within the class definition:
Copy
Embed
classDiagram
class Shape{
<<interface>>
noOfVertices
draw()
}
class Color{
<<enumeration>>
RED
BLUE
GREEN
WHITE
BLACK
}
Comments
Comments can be entered in a class diagram and will be ignored by the editor. Comments must be on their own line and must begin with a double percent sign (%%). All text up to the next line will be treated as a comment, including any class diagram syntax.
Copy
Embed
classDiagram
%% This whole line is a comment classDiagram class Shape <<interface>>
class Shape{
<<interface>>
noOfVertices
draw()
}
Setting the direction of the diagram
You can use a direction statement to set the rendering direction of a class diagram:
Copy
Embed
classDiagram
direction RL
class Student {
-idCard : IdCard
}
class IdCard{
-id : int
-name : string
}
class Bike{
-id : int
-name : string
}
Student "1" --o "1" IdCard : carries
Student "1" --o "1" Bike : rides
Interaction
A click event can be bound to a node. The click event can trigger a JavaScript callback function, or open a link that will load in a new browser tab. Note: this feature is disabled when using securityLevel='strict' and enabled when using securityLevel='loose'.
You can define these operations on a separate line after all class declarations.
Copy
Embed
action className "reference" "tooltip"
click className call callback() "tooltip"
click className href "url" "tooltip"
- action is either link or callback, depending on the type of interaction you want to invoke.
- className is the node id associated with the operation.
- reference can be a URL link or the name of a callback function.
- (Optional) The tooltip is the string displayed when the mouse hovers over the element.
- The callback function will be called with nodeId as a parameter.
Note
A note can be added to the diagram using note "line1 line2". A note can be added for a specific class using note for <CLASS NAME> "line1 line2".
Example
Copy
Embed
classDiagram
note "This is a general note"
note for MyClass "This is a note for a class"
class MyClass{
}
URL link:
Copy
Embed
classDiagram
class Shape
link Shape "https://www.github.com" "This is a tooltip for a link"
class Shape2
click Shape2 href "https://www.github.com" "This is a tooltip for a link"
Configuration
Member box
The empty member box of a class node can be hidden by changing the hideEmptyMembersBox value of the class diagram configuration.
Copy
Embed
---
config:
class:
hideEmptyMembersBox: true
---
classDiagram
class Duck