Polymorphism comes about through inheritance and overriding in classes.

Sometimes one of the methods in a class are unsuitable and as a result we might code an alternative for that method when we write a sub-class. An example might be that a return value might be an integer and in this case a double is needed, or output might need to be displayed differently.

When this happens we have two objects instatiated from the same super-class which behave differently. This is the essence of polymorphism.

In this example a superclass called shape has methods draw and getArea which are overridden when an object is instatiated from the circle or square subclasses. So the behaviour of these methods is different depending on the shape; aCircle.draw() will be different to aSquare.draw() and Java can differentiate between them.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License