What's the difference between inheritance and composition, and also how to apply them in codes | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

What's the difference between inheritance and composition, and also how to apply them in codes

18th Jan 2018, 2:41 PM
AWI
AWI - avatar
3 Answers
+ 4
With inheritance you *are* a "type of baseclass", with composition you *have* a "type of other class". E.g. a student *is* a person, so in a program you might want student to inherit from person. If you would use composition here, a student would *have* a person, that would be weird. Inheritance also makes sure you get all the data and behaviour of your baseclass. That same student might *have* a course that he/she is following. For this you might want to use composition, as inheritance would be weird. Obviously a student is not a course. Inheritance would also mean getting all data and behaviour, so with inheritance our student would for instance get a "SetMark" method. With composition you could say: student.course.SetMark(...). Does this make sense?
19th Jan 2018, 10:56 AM
Freddy
+ 4
Yeah. Thanks Freddy 👍👍
19th Jan 2018, 11:52 AM
AWI
AWI - avatar
+ 1
an example where composition might be a better solution could be a class Pants and a class Pockets. composition meaning that the class is composed of something. so a class pants would have other classes that make up the class pants. so inside of pants you would find an instance of pockets. maybe an instance of zipper, and even belt loops. where you could maybe have the pants extend clothing you would have them use composition for the pockets, zippers and belt loops.
8th Dec 2018, 3:31 AM
John Anderson
John Anderson  - avatar