next up previous
Next: Class hierarchy Up: Unit 08 Previous: Overriding of methods: example

Polymorphism

The overriding of methods causes polymorphism, which means the presence in a class hierarchy of methods with the same signature that behave differently.

Consider the following program.

public class StudentPolymorphism {
  public static void main(String[] args) {
    Person p = new Person("Daniele", "Roma");
    Student s = new Student("Jacopo", "Roma", "Engineering");
    Person ps = s; // OK! due to the compatibility rules
    p.printData();
    s.printData();
    ps.printData();    // ??? what does this print ???
  }
}

The method printData() which is effectively called is chosen based on the class the object belongs to, and not based on the type of the variable denoting it. This mechanism for accessing methods is called late binding.

In the above example, the method called on the object ps will be the one defined in the class Student, i.e., the one that prints name, residence, and faculty. In fact, if we execute the program, it will print:

Daniele  Roma
Jacopo  Roma  Engineering
Jacopo  Roma  Engineering


next up previous
Next: Class hierarchy Up: Unit 08 Previous: Overriding of methods: example