Subtype Polymorphism

The biggest idea of the last couple of lectures: Subtype Polymorphism

  • Polymorphism: “providing a single interface to entities of different types

Consider a variable deque of static type Deque:

  • When you call deque.addFirst(), the actual behavior is based on the dynamic type.
  • Java automatically selects the right behavior using what is sometimes called “dynamic method selection”.

Subtype Polymorphism vs. Explicit Higher Order Functions

Suppose we want to write a program that prints a string representation of the larger of two objects.

Explicit HoF Approach

1
2
3
4
def print_larger(x, y, compare, stringify):
if compare(x, y):
return stringify(x)
return stringify(y)

Subtype Polymorphism Approach

1
2
3
4
def print_larger(x, y):
if x.largerThan(y):
return x.str()
return y.str()