0

I have seen many class diagrams on popular websites and design courses defining the relationships using composition like: Admin has a person instance Umpire has a person instance

As per me, shouldn't it be the case of inheritance as admin 'is-a' person, umpire 'is-a' person. Admin extends Person Umpire extends Person

Can you please help me understand why we are preferring composition here?

1 Answers1

0

Generally speaking, Composition is always favored over Inheritence. Except for the times you want to override methods of the superclass.

I believe there are two reasons for that.

  • You can use only one class for extending so you will have more options for later on when using the composition.

  • The principle for encapsulating. What you want is to encapsulate data as much as you can. You don't want to make the Umpire class inherit from Person just for the sake of accessing Person's attributes. Inheritance usually implies that you want to override a method to use polymorphism and different behaviors for different subclasses. If you want to access a class's data you'll usually do it with an association or in case you want persistent data you'll use composition.

That's why you use composition when talking about Umpire and Admin classes since they don't change the behaviors of the Person class even though there's a noticeable 'is-a' relationship.