Coffeehouse Post

Single Post Permalink

View Thread: Interviewing programmers
  • User profile image
    Dr Herbie

    W3bbo wrote:
    Dr Herbie wrote:
    "What is polymorphism and why is is useful?"

    I was shocked at the number of candidates that couldn't separate polymorphism from class inheritance and I don't think I've met one yet who could explain why it was useful (other than inheriting functionality, which is not the correct answer).

    It's useful because it enables code-reuse and overriding older/irrelevant methods.

    But they're not so much separate as they are dependent. Polymorphism depends on inheritance. That's why VB6 isn't a true OOP language.

    OK, firstly polymorphism has nothing to do with code-reuse.  That's where you're confusing class inheritance with polymorphism (although you're right, polymorphism does depend on inheritance). Polymorphism can also be done through pure interface inheritance.
    Polymorphism is where different classes can be made to appear the same through casting to a base class/interface. This allows all the references to be treated the same, thereby simplifying code that uses those objects.

    The classic example is a vector drawing program there all the shapes derive from the base 'BaseShape'.  The specific instances of shapes that the user creates (Like CircleShape, TriangleShape and RectangleShape) are stored in a collection of BaseShape instances and the picture is drawn by iterating through all the BaseShape instances and caling the 'Draw' method.  The main program has no knowledge of which shape it is drawing and it treats them all the same.
    The contents of the 'BaseShape' class are irrelevant to the technique of polymorphism; BaseShape may containa lot of shared code, or it may be an interface with no shared code. Polymorphism and code-reuse are two separate aspects of inheritance.

    I had been doing OOP for nearly 10 years before I realised this distinction.

    The next question would be:
    Other than inheritance, how else can you re-use code in an OOP fashion?