Association vs InheritanceΒΆ

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 sections (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 sections.

../_images/course.png

Figure 2: A UML Class Diagram showing Association

If you aren’t sure if a class should inherit from another class ask yourself if you can substitute the child class type for the parent class 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.

Check your understanding

10-2-1: A bookstore is working on an on-line ordering system. For each type of published material (books and movies) they need to track the id, title, author(s), date published, and price. Which of the following would be the best design?






10-2-2: A movie theater has multiple showings of a movie each day. What should the relationship be between the Movie class and the MovieShowing class?




10-2-3: What Java keyword is used to specify the parent class?





10-2-4: Question: Which of the following reasons for using an inheritance heirarchy are valid?
  1. Methods from a superclass can be used in a subclass without rewriting or copying code.
  2. Objects from subclasses can be passed as arguments to a method designed for the superclass
  3. Objects from subclasses can be stored in the same array
  4. All of the above
  5. None of the above