0

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?

Example UML diagram labelling the relationship in question

1
  • 2
    " I can't do an association relationship because Person it's a abstract class" - of course you can, it doesn't matter that Person is abstract. The association relationship means that you are associated with the abstract type (your Class2 "sees" only the methods and properties in the Person type, because your 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. Feb 9, 2021 at 16:03

1 Answer 1

2

First of all, your diagram does not correspond to the narrative:

  • In your diagram, Person inherits from Person2. So Person2 would be an anonymous person without any name. Not very useful.

    To letPerson2 inherit from Person (in UML-speak we say that Person2 is a specialization of Person), you must have the triangle arrow head on the side of Person. Note that Person2 has a name, but it's not directly accessible: it can only be accessed via public methods of Person, 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.