How do you read a UML class diagram, and what do the symbols tell you about the Java code to write?
A UML class diagram is a picture of the classes in a system. It shows what each class holds, what each class can do, and how the classes are connected to each other.
public class Main {
public static void main(String[] args) {
Order order = new Order("Ada");
order.add(new OrderLine("Book", 12.0));
System.out.println(order.total());
}
}
And here is the same thing as a diagram. The box for Order has three parts. The top part has the name, the middle part has the attributes and the bottom part has the methods.
+-----------------------+
| Order |
+-----------------------+
| - customer: String |
| - lines: List<Line> |
+-----------------------+
| + total(): double |
| + add(line: Line) |
+-----------------------+
And the signs in the diagram tell you things about the Java code.
the sign what it means in Java
------------------------ --------------------------------------------
a plus sign public
a minus sign private
a pound sign protected
a tilde package-private
an underline static
italics an abstract method or an abstract class
a shape like a triangle an interface
And the lines between the boxes tell you the relationships.
the line what it means
------------------------------ --------------------------------------------
a solid line it holds a reference to it
a line with an open arrow it uses it
a dashed line it uses it only sometimes
a line with a diamond it owns it, the whole part
So the diagram for the order code looks like this.
Order "1" *-- "1" OrderLine
Order "1" *-- "1" Customer
And that line is telling you that one order has one customer and many order lines, and that the order holds the references to both of them.
And there is one more symbol that is worth knowing about, and it is the arrow with an open head. That one says that the class at the arrow end depends on the class at the other end. So the Order points at the OrderLine and that means the order knows about the line but the line does not know about the order.
So the rule to remember is this. The box tells you the fields and the methods, and the lines tell you who holds whom.
The last question in this topic is about the main symbols.