UML Clinic

Purpose

All Java and C++ programmers should know how to easily translate between UML class diagrams, Java or C++ class declarations, and domain descriptions:

This clinic assumes readers have already been introduced to UML class diagrams, but feel they need a little more practice using them.

Work through the following problems. Diagrams can be drawn by on paper or a whiteboard, or by using a CASE tool like StarUML or BOUML. (It is also important for programmers to be familiar with some CASE tool.) Class declarations should be made using a decent text editor such as TextPad and compiled and run using the SDK tools javac and java. Do not use an IDE such as Eclipse or NetBeans since they do packaging automatically.

A programmer familiar with UML should be able to do each problem in about two minutes.

Types of Class Diagrams

There are ten types of UML diagrams. In this clinic we only focus on class diagrams.

There are three unofficial types of UML class diagrams: package diagrams, object diagrams, and pure class diagrams.

From now on the phrase "class diagram" will be understood to be shorthand for "pure class diagram".

Package Diagrams

A package diagram contains packages and dependency arrows. For example, the sentence:

The ui package depends on the business package.

Would be modeled by the following package diagram:

This diagram implies that some of the classes in the ui package depend on (i.e., reference, use, extend, etc.) some of the classes in the business package. For example, the ui package might contain a class called AccountView which references a class called Account that's declared in the business package:

Problem P1

Declare AccountView and Account in Java. Assume Account has a single private field called balance and methods for setting and getting this field. Assume AccountView has a single method called display that prints the balance of its account in the console window. Write a third class called TestAccountView with a main method that creates an account with balance $123.45 and a view of that account. Then main calls the display method of the view.

To do this problem right, you must declare two packages: ui and business. These packages correspond to directories called ui and business. These directories should be subdirectories of a directory called packages, which is listed on your classpath. TestAccountView doesn't belong to a package. More correctly, we say that TesatAccountView belongs to the default or no-name package. The file TestAccountView.class lives in a directory called tests, which is not a subdirectory of packages.

Do not use Eclipse, NetBeans, or any other IDE to do this problem. Use TextPad instead (not NotePad). If you do not have TextPad, download it NOW.

Object Diagram

An object diagram contains objects and links. For example, the sentence "The role of Neo is played by the actor Keanu Reeves" would be modeled by the following object diagram:

Note that the link has no arrow heads. This might just be a defect of StarUML. To get around this I sometimes use a dependency arrow to represent links:

An object diagram instantiates a (pure) class diagram. For example, either of the above object diagrams instantiate the following (pure) class diagram:

The object diagram might be created in memory by the following lines of Java code:

Role neo = new Role();
Actor reeves = new Actor();
neo.playedBy = reeves;

Problem O1

Create the classes Actor and Role. The Actor class has a private field called name and the Role class has a private field called playedBy. Provide getter and setter methods for these fields. These classes should have toString methods. These classes should belong to a package called film. The files Actor.class and Role.class should be in the film subdirectory of the packages directory (see Problem P1). Create a class called TestRole that has a main method that  creates the following scenario:

The roles of Ted, Neo, and Buddha are played by the actor Keanu Reeves.

The TestRole class belongs to the default package and the file TestRole.class is in the tests directory.

Do not use Eclipse, NetBeans, or any other IDE to do this problem. Use TextPad instead (not NotePad). If you do not have TextPad, download it NOW.

(Pure) Class Diagrams

A pure class diagram contains classes, interfaces, and arrows. There are six types of arrows: generalization, dependency, realization, association, aggregation, and composition. You need to know when and how to use all six and how they are translated into Java.

Problem C1

Draw a single UML class diagram that models the following sentences:

1) A implements B.

2) B extends C.

3) A extends D.

4) A depends on E.

5) Every instance of A uses 3 instances of F. Every instance of F is used by 2 instances of A.

Problem C2

Draw a UML object diagram showing two instances of A using three instances of F.

Problem C3

Translate the diagram from C1 into Java class declarations. Place all of these declarations in a single file called TestA.java. Include a class called TestA with a main method that creates the objects described in your diagram from C2. The main method should print some message like "done" when it's finished. Note that other than main you do not need to declare any methods in this problem.

Problem C4 (Reverse Engineering)

Reverse engineering is the process of translating class declarations (in Java, C++, etc.) into a UML class diagram. (Generating declarations from UML is called engineering.)

Translate the following Java class declaration into a UML class diagram:

class Adult extends Person {
   private Adult spouse;
   private Set<Person> children;
   protected double income;
   public Phone[] phoneNumbers = new Phone[3];
   private boolean male;
   private String fname, lname;
   private Date birthDay;
   public int getAge(String units) {
      // computes age in units = years, months, or days
      return 0; // for now
   }
}
  

Problem C5 (Domain Modeling)

Domain modeling is the process of translating a description of some domain into a UML class diagram. (This is commonly done during the analysis phase of software development.) Examples of domains include science, engineering, business, sociology, health care, government, military, etc. Domains often correspond to packages in UML.

Translate each sentence into a UML class diagram. Each diagram should be placed in a separate package. The name of the package should be the name of the domain.

1) Person X is the parent of Person Y.

2) A cat is a mamal. A canary is a bird. Birds and mamals are animals. Cats eat birds.

3) A triangle has three vertices.

Problem C6

Using the class diagrams above as a guide, translate each sentence into a UML object diagram:

Joe is the father of Ed.

Sylvester eats Tweety.

Triangle T has vertices v1, v2, and v3.

Problem C7: Showing Details

A UML class icon allows us to show details such as attributes (primitive typed fields) and operations (methods without their implementations). In addition, we can show the scope of an attribute or operation (public, protected, package, or private). We can also indicate if an attribute or operation is static and if an operation is abstract. We can show the type and initial value of an attribute and the parameters and return type of an operation.

Translate the following Java declaration into a class diagram:

abstract class GUIComponent {
   protected int xc = 10, yc = 10; // position of bounding box
   protected int width = 10, height = 10; // size of bounding box
   static long NEXT_OID = 500;
   private long oid = NEXT_OID++;  // unique object ID
   private static final int OID = 500;
   public boolean move(int x, int y) {
      xc = x;
      yc = y;
      return paint();
   }
   public void grow(int dw, int dh) {
      width += dw;
      height += dh;
      paint(); // no return
   }
   // returns true if successful:
   abstract public boolean paint();
}

Problem C8: Aggregation, Composition, and Types of Aggregation

Recall that aggregation is the relationship between a container and its members:

Composition is the relationship between an assembly and its parts:

There are four types of aggregations: collections (aka bags), lists (aka sequences), sets, and sorted sets. Here is how they differ:

Aggregation    Ordering       Members are unique
Collection     unspecified    unspecified
Set            none           yes
SortedSet      natural        yes
List           by user        no

"Unspecified" means that the value can be anything. "Natural" means that the members can be compared and are sorted from "least" to "greatest" or vice-versa. "By user" means that members have positions in the list that are assigned by the user.

These types of aggregation correspond to interfaces in the Java Collections Framework:

Translate each sentence into a UML class diagram. Label the aggregations with the appropriate constraint: {Collection}, {Set}, {SortedSet}, or {List}.

1) An engine contains 4, 6, or 8 pistons.

2) A document contains words.

3) A dictionary contains words, and every word has one or more definitions.

4) A musical score contains notes.

5) A box contains ballots.

6) A schedule contains appointments.

7) A control panel contains controls.

8) A zoo conains animals.

9) A molecule contains atoms.

10)A week contains days.

11)A roster contains names.

12)A glump holder contains glumps.

Problem C9: Heterogeneous Aggregations

In a homogeneous aggregation all members are instances of the same class. For example: A club contains people. A heterogeneous aggregation can contain members of different classes. For example: a zoo contains tigers, monkeys, and giraffes. Often the classes will have some super-type in common that can be used as the basis of the aggregation.

How would you model the following sentences in UML. Include a declaration of the container class:

1) A team contains managers and players.

2) A web page contains text, links, scripts, and images.

3) An inventory contains books and CDs.