Polymorphism: Is this right?

Soldato
Joined
26 Nov 2005
Posts
3,839
Location
Doon the Bay (Newcastle)
Learning OOD and been asked to define a few terms, this is my own interpretation of Polymorphism, is it correct?

Polymorphism:

Polymorphism allows you to have a function in a parent class but is then overriding in the child classes to give different outcomes using the same function inherited from the parent. The child class uses the basic function in different ways for example a calculator in the parent class can be used in one child class to work out wages, while in another class to calculate hours worked. The calculator code exists in the parent class, but does different jobs in the child classes below, saving time and code, the most important part of programming.


Thanks for viewing.
 
Getting there. You've outlined the inheritance and overriding. You will however need to expand on polymorphic messages. You can give an example of using a collection of type Parent to hold Parent objects and objects of its subclasses and work on it from there.
 
The way I like to think of polymorphism is that you define the interface either in a parent class, or explicitly in an interface and then define the functionality in the subclasses.

Imagine your calculator example.
In this case you could define an interface ICalculator as follows

Code:
interface ICalculator
{
    double Calculate(object calculationConditions);
}

Now, you can define many classes that implement ICalculator and thus have to provide their own definitions of the Calculate method.

When you are creating your client that uses the calculator subclasses you can define an object of type ICalculator and set it to which ever of your subclasses is appropriate for the calculation you're doing.

You don't need to care which subclass is actually doing the calculation or what it is doing, all you need to know is that it implements the correct interface and the subclass will do its stuff and calculate the value in the right way.
 
Polymorphism is the ability for objects created from different classes to be able to use the same interface. That is not to say an interface, as in an actual code element interface, but the boundary between the object and the environment - i.e. the literal interface.

Implementations can and do vary greatly from platform to platform, but most have similarities, i.e. abstraction.

Polymorphism is also applicable for objects than can adapt to different interfaces, but this is rarely used, unless it cannot be avoided, as it is (as you can imagine) not great OOD and practice.

A good example of polymorphism is shapes. A parent abstract class Shape, or an interface, may have numberOfSides() or numberOfCorners() etc. accessors, It is then up to the child classes to supply the answers. Triangle.numberOfSides() == 3, Square.numberOfSides() == 4. Etc.
 
Last edited:
Back
Top Bottom