+ 4
What's the difference between inheritance and composition, and also how to apply them in codes
3 Respostas
+ 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?
+ 4
Yeah. Thanks Freddy 👍👍
+ 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.