DEV Community

Teerasak Vichadee
Teerasak Vichadee

Posted on

UML Class Association Explain with Code

Short note about relation in UML class diagram.

Relation and Dependency

Image description

Can turn into TS code like this

class Address {}

class Food {}

class People {
  // for this line People has relation with Address 
  address: Address
  heart: Heart

  // for this line People has dependency with Food
  eat(food: Food) {}
}
Enter fullscreen mode Exit fullscreen mode

Aggregation and Composition

Image description

Can turn into TS code like this

class Heart {}

class People {
  heart: Heart

  constructor () {
    // for this line People has composition with Heart
    this.heart = new Heart()
  }
}

class PeopleGroup {
  peoples: People[]

  // for this line PeopleGroup has aggregation with (alot of) People
  constructor (peoples: People[]) {
    this.peoples = peoples
  }
}
Enter fullscreen mode Exit fullscreen mode

Generalization and Realization

Image description

Can turn into TS code like this

class Animal {}

interface Eatting {
  eat(food: Food): void
}

class People 
  // for this line People is extends (generalization) from Animal
  extends Animal
  // for this line People is implement (realization) from Eatting
  implements Eatting {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
christophe profile image
Christophe T

Nice article. Well done !
Just one remark: shared aggregation (white diamond) does not necessarily imply that there are lots of objects. In fact, UML no longer adds any meaning for shared aggregation compared to a simple association. Wouldn't multiplicity notation (e.g. * on the People end of an association) allow to unambiguously tell that there are many ?

Collapse
 
ilumin profile image
Teerasak Vichadee

Thank you for feedback. Agreed, we should use notation for that use case.