Lecture 10 Subtype Polymorphism vs. HoFs
Dynamic Method Selection Puzzle
Suppose we have two classes:
-
Dog
: Implements bark() method. -
ShowDog
: Extends Dog, overrides bark method.
Summarizing is-a relationships, we have:
-
Every
ShowDog
is-aDog
-
Every
Dog
is-anObject
.- All types in Java are a subtype of Object.
The rules:
-
Compiler allows memory box to hold any subtype.
-
Compiler allows calls based on static type.
-
Overridden non-static methods are selected at run time based on dynamic type.
- Everything else is based on static type, including overloaded methods.
Static Methods, Variables, and Inheritance
You may find questions on old exams, worksheets, etc. that consider:
-
What if a subclass has variables with the same name as a superclass?
-
What if subclass has a static method with the same signature as a superclass method?
- For static methods, we do not use the term overriding for this.
These two practices above are called “hiding”.
-
It is bad style.
-
There is no good reason to ever do this.
-
The rules for resolving the conflict are a bit confusing to learn.
Subtype Polymorpgism
Subtype Polymorphism
The biggest idea of the next couple of lectures: Subtype Polymorphism
- Polymorphism: “providing a single interface to entities of different types”
Consider a variable deque of static type
a.k.a compile-time type
Deque:
-
When you call
deque.addFirst()
, the actual behavior is based on thedynamic type
a.k.arun-time 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:
def print_larger(x, y, compare, stringify):
if compare(x, y):
return stringify(x)
return stringify(y)
Subtype Polymorphism Approach:
def print_larger(x, y):
if x.largerThan(y):
return x.str()
return y.str()
Sometimes called a “callback”.
The above two code blocks are written in python, just to make its meaning clearer.
DIY Comparison
Writing a General Max Function
Suppose we want to write a function max() that returns the max of any array, regardless of type.
public static Object max(Object[] items) {
int maxDex = 0;
for (int i = 0; i < items