Unit 3 · OOP Concepts

3.6Polymorphism

Polymorphism means "many forms": the same method call behaves differently depending on the object that receives it.

The idea in everyday terms

A teacher says "Everyone, hand in your work". The same instruction produces an essay from one student, a drawing from another and a program from a third, because each one knows how to do their own kind of work. The teacher does not need a separate instruction for each kind of student. In code, a single call such as shape.area() gives the right answer for a circle, a rectangle or a triangle, and the calling code does not need to know which shape it has.

Key words in this topic

  • Binding: connecting a method call to the code that will run.
  • Static (compile-time) binding: decided by the compiler, used for overloading.
  • Dynamic (run-time) binding: decided by the JVM from the actual object, used for overriding.
  • Upcasting and downcasting: treating an object as its more general type, or back as its more specific type.
  • instanceof: an operator that tests what type an object really is.

In this section