Pictures are often helpful when designing software. One particularly useful picture is the class diagram. A class diagram shows the key features of a class including:
- the class name
- the class attributes
- the class methods
Figure 2.2 - General form of a Class diagram
A software class consists of attributes (think of these as nouns) and methods (think of these as verbs).
An attribute, or instance variable, represents a property of an object.
A method is an operation that can be performed upon an object. It is useful to picture the attributes and methods as a class diagram with the following general form.
The class diagram is a rectangle with three compartments separated by horizontal lines. The top compartment contains the name of the class. The middle compartment lists the attributes of the class, and the bottom compartment shows the class methods. This class notation is part of the Unified Modeling Language (UML). UML is the most widely used set of notations in today’s software engineering industry. A diagram for the DrawSquare
class is shown below.
Figure 2.3 - Class diagram for the DrawSquare
class
The methods of the class are listed in the bottom compartment of the class diagram. One of the methods in the DrawSquare
class has the same name as the class (DrawSquare()
). It may seem strange for a method to have the same name as its class, but this is how you give instructions on how to create objects of this class. This is called a constructor.
The DrawSquare
class also makes use of another class: DrawingTool
(the class of the myPencil
object). The class diagram for this class is shown in Figure 2.4. This figure illustrates a couple of new notations that are typical of class diagrams.
The “...” notation shown within the class diagram indicates that the list of methods is incomplete. There are more methods in the DrawingTool
class that are not shown, because they are not relevant to the discussion.
UML diagrams frequently include labels within “<< >>” symbols to categorize the class methods. In Figure 2.4, the DrawingTool()
method is categorized as a constructor method while down
, forward
, and turnLeft
are modifier methods. The distinction between constructor and modifier categories will be covered in a later lesson.