Implementing Class Diagrams in Java
Implementing Class Diagrams in Code
A UML class diagram describes types, their members, and relationships among their objects. Implementing class diagrams in code means preserving that structure and its constraints in a programming language. Here, Java provides the concrete syntax. Your task is to translate what the diagram specifies, then supply the initialization and validation needed to make the resulting objects valid.
Read the class compartments
A class rectangle commonly separates its name, attributes, and operations. Translate an attribute into a field with an appropriate type and access modifier. Translate an operation into a method whose parameters, return type, and visibility match its signature.
Diagram notation | Java member declaration | Meaning |
|---|---|---|
- name: String | private String name; | Restricted access to the field |
+ size(): int | public int size() | Public operation |
# reset(): void | protected void reset() | Package access and restricted subclass access across packages |
~ code: int | int code; | Access within the same package |
An underlined member represents class-level state or behaviour and normally maps to static. An ordinary instance field belongs separately to each object. Do not add setters automatically: a setter may permit changes that contradict the model.
Constructors often require implementation decisions because a diagram need not list them. Use constructors to establish required fields and links before an object becomes available to clients.
Translate type relationships
A generalization relationship expresses an “is a” relationship. In Java, a subclass uses extends to name its superclass. Interface realization uses implements to name a contract the class fulfils.
class Invoice extends Document implements Printable {
// Fields, constructor, and required method implementations
}Java permits a class to extend one class and implement multiple interfaces. An abstract class uses abstract; it cannot be instantiated directly. A concrete subclass must implement any abstract methods it inherits unless a suitable implementation is already inherited.
Represent association ends
An association end's multiplicity specifies how many related objects are permitted for one object at the opposite end. For a finite lower bound L, upper bound U, and actual number of links n:
Read the bound beside the target class when deciding how many target references one source object needs. An asterisk means there is no specified finite upper bound.
Target multiplicity | Possible Java representation | Additional responsibility |
|---|---|---|
1 | One reference | Reject a missing target |
0..1 | One nullable reference | Handle the absent case |
0..* | Collection or array | Preserve any specified uniqueness or ordering |
2..5 | Collection or array | Check both size bounds |
The arrow indicates navigability from Playlist to Track. It supports storing track references in a playlist; it does not require a reverse playlist field in each track. Multiple playlists can reference the same track without creating separate track objects.
Preserve constraints after construction
An invariant is a condition that remains true whenever an object is available for normal use. A non-null field, a bounded number of links, and agreement between two stored association ends can all be invariants.
A Java field type alone does not enforce a UML multiplicity. A reference can contain null, and an array can have an unsuitable length. Check required links and bounds explicitly. For bidirectional associations, coordinate updates so both stored ends agree.
Protect validated state from later changes. For example, copying an incoming array prevents the caller from replacing its entries through the original array. Returning a copy similarly protects the stored array. These copies still refer to the same associated objects.
A composition diamond adds ownership and lifecycle semantics. Java has no composition keyword: reference access, ownership rules, and explicit removal behaviour must implement the required semantics. Garbage collection alone does not establish them.
What to remember
- Translate member signatures and visibility before adding implementation details.
- Use extends for class generalization and implements for interface realization.
- Read multiplicity at the target end for each source object.
- Enforce constraints during construction and every permitted update.
Example: Implement a project-team roster
A project application needs a Team class implementing the association below. Each team has two to five distinct member objects. A member may belong to several teams. Membership is fixed after construction, and clients may read the roster. Assume Member is an existing class, uniqueness means different object identities, and execution uses one thread.
a) Choose a Java field representation and identify the required validation rules. Use an array for this implementation.
The target association end is the typed role reached through a relationship; here it is members, whose objects have type Member. For one team, the minimum permitted membership is ________ and the maximum is ________.
An appropriate field is:
private final Member[] members;The array holds references to the existing members, allowing another team to reference the same objects. Validate that the supplied array exists, its length is between two and five inclusive, every entry is non-null, and no two entries refer to the same object.
The field is private to control access. The final modifier prevents reassignment of the field, but it does not prevent changes to array entries. Therefore, a private final array plus controlled access and validation is the required representation, rather than final alone.
b) Implement a constructor and a public getMembers() operation that preserve these rules without exposing the stored array.
First make a defensive copy, a separate container that prevents changes through the caller's container from altering stored membership. Validate that copy, then assign it to the field. Return another copy when clients request the roster.
import java.util.Objects;
public final class Team {
private final Member[] members;
public Team(Member[] initialMembers) {
Member[] copy = Objects.requireNonNull(
initialMembers, "members array"
).clone();
if (copy.length < 2 || copy.length > 5) {
throw new IllegalArgumentException("team size");
}
for (int i = 0; i < copy.length; i++) {
Objects.requireNonNull(copy[i], "member");
for (int j = 0; j < i; j++) {
if (copy[i] == copy[j]) {
throw new IllegalArgumentException(
"duplicate member"
);
}
}
}
this.members = copy;
}
public Member[] getMembers() {
return members.clone();
}
}The array check rejects a missing input array. The size check enforces both multiplicity bounds. The outer loop checks each member for null; the inner loop compares it with earlier entries using identity equality, rejecting repeated object references.
The copies protect the array entries, not the internal state of each Member object. That is sufficient for fixed membership: changing a member's own data does not replace its identity in the roster. The completed constructor and accessor preserve the association without creating duplicate member objects.
c) Four team objects have been constructed successfully. Find the minimum and maximum total number of member-reference entries stored in their four internal arrays.
Each array contributes at least ________ and at most ________. Count array entries rather than distinct member objects, because different teams may share members.
For the minimum, put every team at its lower bound:
For the maximum, put every team at its upper bound:
The internal arrays store a minimum of 8 reference entries and a maximum of 20 reference entries. These bounds do not establish how many distinct member objects exist, because sharing across teams is permitted.
A delivery system uses the following UML class excerpt. Each parcel's tracking number is assigned during construction and must never be reassigned afterward.
The initial Java implementation is:
class Parcel {
private long trackingNumber;
Parcel(long trackingNumber) {
this.trackingNumber = trackingNumber;
}
}Complete the implementation rule with one Java keyword: insert immediately before long in the field declaration to make the compiler enforce the stated reassignment restriction.
A document system models Report as a subclass of abstract class Document and as implementing interface Exportable. The declarations are:
abstract class Document {
}
interface Exportable {
String export();
}The diagram requires Report to be a concrete class. Which statements correctly describe its Java implementation? Select every correct statement.