Lecture 10: Subtype Polymorphism vs. HoFs

9/18/2020

Static Methods, Variables, and Inheritance

Subtype Polymorphism

Subtype Polymorphism

Subtype Polymorphism vs. Explicit Higher Order Functions

def print_larger(x, y, compare, stringify): if compare(x, y): return stringify(x) return stringify(x)
def print_larger(x, y): if x.largerThan(y): return x.str() return y.str()

DIY Comparison

shoutkey.com/TBA

Writing a General Max Function: The Fundamental Problem

Solution

public static OurComparable max(OurComparable[] items) {...}
public interface OurComparable { /** Return negative number if this is less than o * Return 0 if this is equal to o * Return positive number if this if greater than o */ public int compareTo(Object obj); } public class Dog implements OurComparable { private String name; private int size; public Dog(String n, int s) { name = n; size = s; } public void bark() { System.out.println(name + " says: bark"); } // Returns negative number if this dog is less than the dog pointed by o, and so forth public int compareTo(Object o) { Dog otherDog = (Dog) o; return this.size - otherDog.size; } } public class Maximizer { public static OurComparable max(OurComparable[] items) { int maxDex = 0; for (int i = 0; i < items.length; i += 1) { int cmp = items[i].compareTo(items[maxDex]) if (cmp > 0) { maxDex = i; } } return items[maxDex]; } }

The OurComparable Interface

General Maximization Function Through Inheritance

Comparables

The Issues with OurComparable

public class Dog implements Comparable<Dog> { ... // Returns negative number if this dog is less than the dog pointed by o, and so forth public int compareTo(Dog otherDog) { return this.size - otherDog.size; } } public class Maximizer { public static Comparable max(Comparable[] items) { int maxDex = 0; for (int i = 0; i < items.length; i += 1) { int cmp = items[i].compareTo(items[maxDex]) if (cmp > 0) { maxDex = i; } } return items[maxDex]; } }

Comparable Advantages

Comparators

Natural Order

Additional Orders in Java

import java.util.Comparator; public class Dog implements OurComparable { ... // Returns negative number if this dog is less than the dog pointed by o, and so forth public int compareTo(Object o) { Dog otherDog = (Dog) o; return this.size - otherDog.size; } private static class NameComparator implements Comparator<Dog> { public int compare(Dog a, Dog b) { return a.name.compareTo(b.name); } } public static Comparator<Dog> getNameComparator() { return new NameComparator(); } } import java.util.Comparator; public class DogLauncher { public static void main(String[] args) { ... Comparator<Dog> nc = new Dog.getNameComparator(); if (nc.compare(d1, d3) > 0) { d1.bark(); } else { d2.bark(); } } }

Comparable and Comparator Summary