Reputation: 753
I am trying to show here that Admin is a sub-class of User which is shown through the open triangle relationship connection. Is this enough to show that the sub-class relies on the main parent class to exist or would I then need to further apply composition? I have shown my example below. I am super confused regarding this. I feel it's enough to show it through the specialization arrow but I am not sure.
Upvotes: 2
Views: 1018
Reputation: 73366
I'd like to add another view to Bruno's excellent and accurate answer regarding generalization.
Yes, it is indeed sufficient to make Admin
a specializatrion of User
: this means that Admin
is a User
. It also means that Admin
inherits User
's non-private properties and operations (i.e. AuthenticateUser()
). Finally it means that an instance a
of Admin
is also an instance of User
and has hence a username
and a password, although these are visible only to User
instances. Unfortunately, once an object created as Admin
, it will always stay an Admin
.
Your hesitation about composition is therefore perfectly understandable: it is often advised to prefer composition over inheritance. You could perfectly imagine to have a User
that has an Admin
role, without Admin
inheriting from User
. But this is a radically different design. And in this specific case, it would be strange, if there wouldn't be other roles as well.
Last but not the least, it's worth to mention de decorator pattern that may combine inheritance with aggregation (instead of composition): In this design, you would make Admin
a decorator of User
: it extends the reponsibilities of the User with Admin
responsibilities (i.e. with additional operations). But this can be done at runtime: you can create a User
, add an Admin
responsibility, or remove the Admin
responsibility. THis is much more dynamic.
Upvotes: 2
Reputation: 32586
Is this enough to show that the sub-class relies on the main parent class to exist or would I then need to further apply composition?
Because of the generalization an Admin is a User, so if there is no User at all (User.allInstances()->size() = 0
) then there is no Admin too. But of course you can have User(s) without having Admin.
If you just want to say that nothing more than the generalization is necessary.
But if you want to indicates an Admin is a User and there is 1 and only 1 admin you can do :
As you can see admin is a property of the class User (isStatic is true) because it is written underlined, no need to have it for all instances (including the admin(s)).
An other way to say the same without using an additional relation is :
Of course if you want to say there is at least one admin and not exactly one just use the multiplicity 1..*
in the first solution or modify the constraint to have {allInstances()->size() >= 1}
in the second solution.
Upvotes: 3