Time estimate: 45 min.

9.1.4. is-a vs. has-a (Day 2)

Another type of relationship between classes is the has-a relationship or association relationship. Use this when the object of one class contains a reference to one or more of another class. For example, a course can have many course periods associated with it as shown below. The 1 near the Course means that 1 course object is associated with the number shown near the other class. In this case it is * which means 0 to many. So one course is associated with 0 to many course periods.


Figure 3: A UML Class Diagram showing Association

In the code, the Course class has an array or ArrayList of CoursePeriod objects as an attribute inside it.

public class Course
    private ArrayList<CoursePeriod> periodList;

Alternatively, we could say that a CoursePeriod has a Course attribute inside it to hold the information about the Course. It is up to the programmer how to design these two classes depending on which type of association would be more useful in the program.

public class CoursePeriod
    private Course courseInfo;
    private int period;

Here is another example. Consider the classes Student, Course, and APcourse. An APcourse is a special type of Course. Students are in Courses. What are the relationships between these classes? The UML diagram below shows the inherits (is-a) relationship between Course and APcourse and the associate (has-a) relationship between Course and Students.


Figure 4: A UML Class Diagram for Student, Course, APcourse

coding exercise Coding Exercise

We can represent the diagram in Figure 4 in the code below. The Course class has an ArrayList of Student objects in it as the roster attribute. And an APcourse extends Course. What do you think the following code will print out?

What do you think the following code will print out?

9.1.5. is-a Substitution Test

If you aren’t sure if a class should inherit from another class ask yourself if you can substitute the subclass type for the superclass type. For example, if you have a Book class and it has a subclass of ComicBook does that make sense? Is a comic book a kind of book? Yes, a comic book is a kind of book so inheritance makes sense. If it doesn’t make sense use association or the has-a relationship instead.


Only use inheritance when the child class is really a type of the parent class, otherwise use association.

exercise Check your understanding

9.1.6. groupwork Programming Challenge : Online Store

Working in pairs or groups, design an online store with classes for Store, ItemForSale, Book, Movie, and Author.

Declare at least 2 instance variables for each of the classes below. Create an inheritance or association relationship for some of them.

9.1.7. Summary

You have attempted of activities on this page