Lecture 10 - 02/08

Subtype Polymorphism vs HoFs

Here is the full code for these Dog related classes and instances. Note the use of the Comparator interface below as well, to allow us to do comparisons such as nameCompare() or sizeCompare().

Highlight: the use of interfaces such as Comparable and Comparator make our code more general and allow us to make callbacks (helper functions such as the helper function compareTo for max below)

import java.util.Comparator;
public class Dog implements Comparable<Dog> {
private String name;
private int size;
public Dog(String n, int s) {
name = n;
size = s;
}
@Override
public int compareTo(Dog otherDog) {
return this.size - otherDog.size;
}
// Implements Comparator interface
public static class NameComparator implements Comparator<Dog> {
public int compare(Dog d1, Dog d2) {
return d1.name.compareTo(d2.name);
}
}
public static class SizeComparator implements Comparator<Dog> {
public int compare(Dog d1, Dog d2) {
return d1.size.compareTo(d2.size);
}
}
}
public class Maximizer {
public static Comparable max(Comparable[] items) {
// Method takes in an array of Comparable type objects
// Returns largest Comparable type object
// Uses the passed Comparable type objects' compareTo method for comparison
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];
}
}
public class DogLauncher {
public static void main(String[] args) {
Dog d1 = new Dog("A", 1);
Dog d2 = new Dog("B", 2);
Dog d3 = new Dog("C", 3);
Dog[] dogs = new Dog[]{d1, d2, d3};
Dog maxDog = Maximizer.max(dogs);
// Using Comparater interface (note similarity to use of Comparable interface)
Comparator<Dog> cd = new Dog.NameComparator();
if (cd.compare(d1, d2) > 0) {
System.out.println(d1.name);
} else {
System.out.println(d2.name);
}
}
}