Class Diagrams
Class diagrams are the foundational structural diagrams in UML. They represent the static view of a system, detailing classes, their internal structure, and how they relate to one another.
1. Anatomy of a Class
A class is represented as a box with three compartments:
- Top: Class Name (Bold, centered, Italics if Abstract).
- Middle: Attributes (Fields/Variables).
- Bottom: Operations (Methods/Functions).
Visibility Modifiers
+Public: Accessible from anywhere.-Private: Accessible only within the class.#Protected: Accessible within class and subclasses.~Package/Internal: Accessible within same package.
2. Relationships and Arrows
Understanding relationships is the core of UML. The arrow style defines the semantics.
| Relationship | Notation | Meaning | Property |
|---|---|---|---|
| Generalization | Solid line + Hollow Triangle | Dog is an Animal. | Inheritance |
| Realization | Dashed line + Hollow Triangle | ArrayList implements List. | Interface implementation |
| Association | Solid line (opt. arrow) | Teacher has Students. | General link |
| Aggregation | Hollow Diamond | Car has Wheels. | ”Part-of” (Weak: Parts can exist alone) |
| Composition | Filled Diamond | Building has Rooms. | ”Part-of” (Strong: Parts die with parent) |
| Dependency | Dashed Arrow | A uses B. | Temporary usage (parameter/local) |
Multiplicity
Multiplicity defines how many instances of one class link to one instance of another:
1: Exactly one.0..1: Zero or one.*or0..*: Zero or more.1..*: One or more.
3. Decisions: Attribute vs. Entity?
A common dilemma: Should something be an attribute of a class or its own entity (class)?
- Attribute: If the data is a simple value (string, number, date) that doesn’t have its own identity or lifecycle. E.g.,
String address. - Entity: If the data has its own properties, needs to be shared among multiple objects, or has a complex lifecycle. E.g.,
Addressas a class if you need to trackStreet,City, andZipseparately or validate them.
4. Comprehensive Example
PlantUML Code:
interface Playable {
+play()
}
abstract class Instrument {
-String brand
#float price
{abstract} +tune()
}
class Guitar extends Instrument implements Playable {
-int stringCount
+play()
+tune()
}
class Case {
-String material
}
Guitar "1" *-- "1" Case : has >
Guitar "1" o-- "0..*" String : uses >
System Diagram
Mapping to Code (Java)
public interface Playable {
void play();
}
public abstract class Instrument {
private String brand;
protected float price;
public abstract void tune();
}
public class Guitar extends Instrument implements Playable {
private int stringCount;
private Case storageCase = new Case(); // Composition
public void play() { /* ... */ }
public void tune() { /* ... */ }
}