10.4 Summary

10.4 Summary

Natural Order (Python vs. Java)

Today we’ve seen polymorphism and function passing.

For comparing two objects using an intrinsic order (a.k.a. a natural order), Python uses a form of polymorphism called operator overloading. Java instead uses subtype polymorphism.

class Dog:
   def __init__(self, name, size):
       self.name = name
       self.size = size
  
   def __gt__(self, other):
       return self.size > other.size
public class Dog implements Comparable<Dog> {
   ...
   @Override
   public int compareTo(Dog uddaDog) {
       return size - other.size;
   }
}

Note: Python is duck typed: Do not have to specify if > is available or not.

Other Orders (Python vs. Java)

For comparing two objects using an alternate order, Python uses function passing, i.e. you provide a key function. By contrast, Java uses subtype polymorphism, just like for intrinsic orders. We package the comparison function in a Comparator object.

class Dog:
   def __init__(self, name, size):
       self.name = name
       self.size = size

def name_len(dog):
   return len(dog.name)

max_dog=max(doglist, key=name_len)
public static class NameComparator 
          implements Comparator<Dog> {
   @Override
   public int compare(Dog a, Dog b) {
       return a.name.compareTo(b.name);
   }
}

Writing Library Functions

If we want to write the code that actually uses a Comparable or Comparator, then we'll find the method specifications get a little vexing, for example:

public class Maximizer {
   public static <T extends Comparable<? super T>> T max(T[] items) {
		...
   }
}

Luckily for you, you won't have to deal with this much, other than at the end of Project 1B.

Last updated