I was creating a class model using inheritance, and have a situation I don't know how to represent.
For this question I built an example diagram in which I have a class Person
with some attributes.
I also have a class Class1
that needs to use objects of a new class with Person
's attributes plus sex
and birthDate
attributes, so I create a Person2
class which inherits from Person
.
But I also have another class Class2
which needs to use objects with only the Person
attributes, not Person2
. I can't use an association relationship because Person
is an abstract class.
How should I handle this situation?
1 Answer 1
First of all, your diagram does not correspond to the narrative:
In your diagram,
Person
inherits fromPerson2
. SoPerson2
would be an anonymous person without any name. Not very useful.To let
Person2
inherit fromPerson
(in UML-speak we say thatPerson2
is a specialization ofPerson
), you must have the triangle arrow head on the side ofPerson
. Note thatPerson2
has aname
, but it's not directly accessible: it can only be accessed via public methods ofPerson
, since it's private.Your diagram does not give any clue about
Person
being abstract. The usual way is to write the name of abstract classes in italic.
After correction, it would look like: enter image description here
Class2
may perfectly be associated with an abstract class. The only thing that Class2
may not do in this case, is to instantiate (i.e. create an object of) the Person
. But it may very well get the Person
object from somewhere else. For example: since Person2
is a Person
, a Class1
object may invoke a method of a Class2
object passing person
as a Person
parameter. Or Class2
could use an injected factory that would create instances of concrete specializations of Person
.
There are plenty of practical uses of associations with abstract classes. For example, it's used for making observers, or the more complex interpreter pattern.
Explore related questions
See similar questions with these tags.
person: Person
attribute has that type), but you can assign a Person2 instance to the variable (that's what inheritance allows you to do - substitute a derived type where an object of the base class is expected). P.S. your inheritance arrow should go from Person2 to Person.