"Danny Ni" <dn**@yahoo.com> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...
Hi,
I was asked about the advantages of polymorphism in a recent job
interview. What are they? I couldn't think of anything, so I answered it's just an
option programmer can make use of in an OO design.
As an example, say you have an office application that contains a Word
document class, an Excel document class, and a PowerPoint document class.
You could design an interface (call it "IDocOutput"), define a Print()
method in that interface, and then declare each of the document classes as
implementing that interface. This forces you to implement a Print() method
in each of the document classes. It also allows you to treat an instance of
any of the three document classes as an instance of IDocOutput. You could
then write a function somewhere called "PrintDocument(IDocOutput theDoc)"
and inside this function simply call "theDoc.Print()". In the
PrintDocument() function you don't need to worry if the document is Word,
Excel, or PowerPoint.
An alternative to doing this without Polymorphism would be to separate print
handler for each document and have some conditional logic to choose between
them. In doing so you would probably have duplicated code, which is not
good, right? Also, by designing an interface to expose only those methods of
a class that are relevent in a given context, you are reducing the
opportunity of doing something bad with an object.
In the end it usually boils down to code reuse, maintainability, and
robustness, and polymorphism helps promote all of those.