Why is inheritance an important aspect of object oriented programming?

Recommended Answers

All 4 Replies

Consider this:

Say (just pretend) you have a objects called CD with the following attributes:

shape
size
capacity

[Actions/Methods]
Spin
Record

Then you would have to implement all of those properties and actions. Now say you wanted an object called DVD with the exact same attributes. Ordinarily, you would have to reimplement all of those attributes, even though shape, size, and Spin are the same.

Using inheritance, you can "inherit" DVD from CD and automatically get all of its attributes; the only ones you would have to re-implement are capacity and Record since they are different.

That's what inheritance does in a nutshell. It allows you to reuse the code of other objects where the code would be exactly the same.

Note: I don't vouch for the technical correctness of my example.

commented: nice example +6
commented: Good explanation +4

Just to add to scru's point: Being able to re-use code is an extremely important but sometimes overlooked feature of programming. Its main value is not saving time, but eliminating bugs.

That is, if the code for CD works provably correctly (or testably correct even), then a DVD class built on top of it will be solid so long as DVD doesn't muck with the internals.

Jeff

commented: indeed +5

Just to add to scru's point: Being able to re-use code is an extremely important but sometimes overlooked feature of programming. Its main value is not saving time, but eliminating bugs.

That is, if the code for CD works provably correctly (or testably correct even), then a DVD class built on top of it will be solid so long as DVD doesn't muck with the internals.

Jeff

Case in point are Python's own modules, thoroughly tested and optimized. You can inherit any of those classes into your own class and customize from there.

And you can add to things as well and change things around. So you can have a class of Line, that has:

Attributes
start
end

And if you wanted to make box, well a box is just a complicated set of lines, so if you inherit from lines then you already have some stuff sorted out, though you can overwrite anything in lines by redefining it in box.

So box could have

Attributes
list_of_lines
area
curcumference

And then you can have a cube, which is just a number of boxes joined together, i guess i should have called box square huh? BUt it means that when making the cube you do not have to worry about lines, they are already dealt with, you do not worry about the squares being put together, they are already working, so all you have to do is work out the arrangement of the squares.

Classes generally are there and tend to (if used well) make your job a lot easier.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.