Wednesday, July 23, 2014

Relations between Classes

I am going to use examples from two projects, both on GitHub. The BookList example and the JListExample.

There are four basic types of relations between classes.

* Association
* Inheritance
* Aggregation
* Compositon

Association

Association is probably the most common relationship between classes. It exists when a class talks to another class by calling a method in that other class. In the JLIst example The Swing form has this relationship with ItemsList class. Association is shown with a simple line drawn between classes. Here is a diagram. (Note, I have only included the fields and methods that are immediately relevant.)

Here is the relevant code. The first is the constructor where the class is intitialized. The second from the private class of the action listener where the class is used to get a copy of the array list

public Mainform(){
  //Initialize the form and the ItemList 
  //in the constructor
  createFrame();
  iList = new ItemList();
 }

. . .

if (list.getSelectedIndex() != -1) {
            
//No selection, disable fire button.
              
 String name=list.getSelectedValue();
            
Item i = iList.getItem(name);

Inheritance

We have discussed inheritance. Inheritance is a parent/Child, general/specific kind of relationship. It it represented by a line with a triangle at one end. The triangle always points toward the parent in the relationship. You should also note that the relationship between a class that implements and interface and the interface is also represented as inheritance with the triangle always pointing toward the interface. Sometimes the line is dashed to distinguish it from regular inheritance.

Aggregation

Unlike Inheritance which represents a general/specific relationship, Aggregation represents a whole/part relationship.In the JListExample, the ItemList is the whole and the Items are the part. Aggregation assumes that the part can exist independently of the whole. Aggregation is represented by an empty diamond. The diamond always points to the whole.

Composition

Just like aggreagation, composition is a whole/part relationship. The only difference is that in composition the parts cannot exist independently from the whole. The ActionListener classes have this type of relation to the swing form. If the form is destroyed the listeners also go away. The line for composition has a filled in diamond. Again the diamond always points to the whole.

No comments:

Post a Comment