Intro to Class Diagrams

Class Diagrams

Previously we looked at how Java (and Python) implement classes. The idea of a class is not unique to Java, so programmers have created a shorthand, pictorial way of representing classes called class diagrams. Below is an example of a class diagram for a Circle Class:

The rectangle on the left is the class diagram. The other two rectangles demonstrate how to read a class diagram.

A class diagram consists of 3 sections:

  1. The top is the name of the class (required)
  2. Middle section instance variables (optional, only if there are no variables necessary to the class)
    • A + before the variable name indicates public access (i.e. anyone can directly access the variable). This is generally regarded as bad practice.
    • A - before the variable name indicates private access (i.e. only the class can directly access the variable). This is considered better practice.
    • A # before the variable name indicates protected access. More on in another lesson.
  3. The last section is for methods (optional, only if there are no methods necessary to the class)

The above class diagram may be implemented as shown below:

public class Circle {
  
 private double radius; // -radius:double
 private String colour; // -colour:String
 
 public Circle() { // +Circle()
  this(1.0, "red"); //Defaults for radius = 1.0, and colour = "red"
 }

 public Circle (double r) { // +Circle(r:double)
  this(r, "red");
 }
 
 public Circle (double r, String c){ // Not Listed! But it should be...
  this.radius = r;
  this.colour = c;
 }

 public double getRadius() { // +getRadius():double
  return radius;
 }
 
 public double getArea() { // +getArea():double
  return Math.PI * Math.pow(radius, 2);
 }
}

Exercise 1:

Unfortunately, this type of circle is a little useless: It can't be changed after you create it. Good coding practice dictates that we create the necessary getters and setters for our instance variables. Create the missing getters and setters for our instance variables.

Also, override (replace) the default toString() method so that the output is as follows: Circle[radius=?, colour=?] Replace the ? with the radius and colour of the circle.

Finally, create a method +getCircumference():double which returns the circumference of the circle.

What should the class diagram for the circle look like now?

Exercise 2

Implement the following Class diagrams as Java Classes