Dynamic Dispatch

[comp1110-8F]

Exploiting the concept of subtyping, object-oriented programming gets its power via dynamic dispatch, which is the idea that when you call a method on an object, it is the run-time class of the receiver object that determines the code of the method, not the type of the receiver at compile time.

This is relatively obvious in the following example (using the definitions of Generalizing Accounts):

Account a = new PointsAccount(); a.deposit(500);

Since Account is an interface where the deposit method has no code, it should be clear that the code executed for deposit is the one defined in the PointsAccount class. Now assume we create a subclass of PointsAccount:

/** * Represents a PointsAccount with a larger deposit bonus */ class PremiumPointsAccount extends PointsAccount { /** * Adds another 10*/ @Override void deposit(int amount) { if(amount<0) { throw new InvalidArgumentException(); } super.deposit(amount * 110 / 100); } }

The point of dynamic dispatch is that even when we could find some code to call based on the type of the receiver (that is, the code in the PointsAccount class), the actual method that will be called is the one of the receiving object at runtime, i.e. the one defined in PremiumPointsAccount.

PointsAccount a = new PremiumPointsAccount(); a.deposit(500);

This is the key idea that distinguishes object-oriented code from non-object-oriented code. Programming languages are called object-oriented when they encourage a style of programming that rely heavily on this feature, as Java does. In contrast, Java code that does not rely on dynamic dispatch is not really object-oriented code.

bars magnifying-glass caret-down plus minus arrow-right xmark