«^»
7.7. Dynamic binding

So far, a reference variable of the type Person has been given values that causes it to refer to a Person object. However, a reference variable can be given a value that causes it to refer to an object of its class or any subclass of that class. For example, in the UseStudent program, the variable tPerson is first made to refer to an object of class Person, but, at the end of the program, it is made to refer to an object of class Student.

So, suppose you have written a method:

0590: public void task(Person pPerson) {
0591:    ...
0592: }
The code of the method task is written in terms of the variable pPerson. We can pass as an argument to task an object that is of class Person or an object that is of any subclass of Person. If the code of task calls a method and this method is one that has been overridden in the subclass, then the actual method that is called will depend on what kind of object has been passed to task. For example, if task calls equals then Person's equals method will be called if the object passed as an argument is of class Person, whereas Student's equals method will be called if the object passed as an argument is of class Student. So the actual version of the equals method that will be called is unknown until runtime: it depends on what kind of object pPerson refers to. This is known as dynamic binding.

The code of the method task will also continue to work if, later, another subclass of Person is produced: the code of task does not have to be modified every time a new subclass of Person is produced.