Home > Software engineering >  How to represent an attribute whose type is a class that many classes inherit from?
How to represent an attribute whose type is a class that many classes inherit from?

Time:11-05

I'm creating a little ORM and I have to make a class diagram using UML. How can I represent that an attribute is an array of instances of classes that inherit from a common superclass, something like this:

class Model {
    public attributes: string[];
}

class User extends Model {}
class Schedule extends Model {}

class Controller {
    private models: Model[] = [new User, new Schedule]
}

How can I model the class Controller in a UML diagram?

I did this:

enter image description here

But I think that is wrong because the class Controller should not have an array of Model instances, the class Controller should have an array of classes that inherit from Model.

CodePudding user response:

A private property model of class Model, but with a multiplicity with no upper bounds can be noted as attribute:

- model: Model [*]

But you can also show it graphically, with an association, telling that each Controller instance may be associated with 0 or more Model instances:

Diagram with 2 associated classes

The - means private, the * is a short cut for multiplicity 0..* meaning at minimum 0 instances and * for no maximum limit.

Edit following the edited question

In the same diagram, you may also say that Model can be specialized further with User and Schedule both inheriting from it:

enter image description here

And this corresponds to what you want to model: it says that a Controller instance can be associated with 0 or more Model instances. But these instances do not have to be direct instances of the super class: In UML when User or Schedule inherits from Model, it means that every instance of User or Schedule is also an instance of Model. Hence the Controller instance can be linked to schedules and users.

By the way: You could make Model an abstract class (Name in italic), to say that there are no direct instances of model, but only instances of its subclasses.

  • Related