Should there be an association for the base class when it's implied?

Viewed 100

I'm trying to make a UML class diagram for a very simple scenario. Consider the following code: List<Food> foods = {new Tomato(), new Pizza()}; as a field to class A. Clearly, class A has associations between Tomato and Pizza, but should it also have an association between Food?

Of course, Tomato and Pizza extend from Food :)

3 Answers

The use of generics such as List<Food> is always a challenge in UML, since the semantics of generics are not the same across the programming languages.

Here, the field foods of class A means that there is a navigable association from A to Food. And Tomato and Pizza are specializations of Food (based on your use of the term "extend"):

UML class diagram

Additional remarks:

  • The association is with Food, because the type is List<Food> and there is no direct coupling between A and Tomato or Pizza.

  • Keep in mind that a class diagram shows the general picture and not a specific scenario with individual objects (that was the purpose of the former object diagram).

  • The use of a list tells that the association can be with be 0 or more Food. But we don't know if one Food object could be used by several A or not (several is theoretically possible if Food would be a reference type): therefore the multiplicity is unspecified on the A side.

  • Based on the semantics, you may consider making the association a composition or an aggregation. But a simple association is correct in any case.

  • Based on the what you want to highlight about your design in the A-to-Food association:

    • you may prefer the dot notation on the Food end, if you want to underline that the association (aka the list) is owned by A
    • you may just use navigability notation as in my diagram, if care less for the current implementation and just want to express that accessing Food from an A should be easy.
    • you may show none of the above, if you want to keep these topics open.

Without seeing more details it's difficult.

Your food is a 0..n multiplicity association.

Both Tomato and Pizza do not have an explicit assocation in that code. So that's just a dependency.

An association is a stronger form of a dependency (sloppy definition that is). Actually you can create an association. It depends on the yet unknown details. If your focus is on the list and you want any subclassed food in it, you would not draw associations to each of these subclasses but only to the parent class Food.

As said: it all depends and as a design template the details from the template need to be more beefy.

I would say your ClassA has a structural relation (association) to Food.

Because it also calls the constructors of Tomato and Pizza it has a dependency to those classes.

Related