[Tutor] [Slightly OT] Inheritance, Polymorphism and Encapsulation

Alan Gauld alan.gauld at btinternet.com
Wed Sep 19 09:07:39 CEST 2007


"Stephen Nelson-Smith" <sanelson at gmail.com> wrote

> "Place the following three in order: Inheritance, Polymorphism, 
> Encapsulation."

Interesting exercise!

> Encapsulation comes with OO - you get it for free.

It comes with OO but not for free. It is a fundamental property of
OOP languages, but not all languages are OOP and trying to
write OO programs in a non OOP language will very quickly
show that encapsulation requires a lot of effort!

> Polymorphism is a hugely important enabler, but this in itself
> is enabled by Inheritance,

Polymorphism is the root of OOP. It is what distinguishes
true OOP from Modular or Object Based programming.
But, it does NOT depend on inheritance, you can do polymorphism
on several levels and in Python we use duck typing to create
polymorphism without inheritance all the time.

Inheritance is an implementation convenience, it saves writing
extra code but that is all.

> this order: Inheritance, Polymorphism, Encapsulation.

I'd go for Encapsulation, Polymorphism, Inheritance.

Without encapsulation you have no objects(*).
Without polymorphism you have no OOP.
Inheritance is convenient.

(*) I use encapsulation in its original sense of binding data
and functions together in a single unit of code - an object.
Not in its frequently seen, but corrupted sense, of data hiding
(using private/public data declatations etc)

> My colleagues felt that of the three options this was the least
> satisfactory, and showed a lack of understanding of OO design.

That goes a bit far, the order is fairly argbitrary, but going by
your reasoning I'd disagree with your choices as explained above.

> even suggested that one could have polymorphism without inheritance.

Absolutely true, see the OOP topic in my tutorial for an example
in Python. Indeed some OOP languages do not support inheritance
but do support polymorphism - Actor is one such.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list