> For the complete documentation index, see [llms.txt](https://cs61b-2.gitbook.io/cs61b-textbook-2025/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cs61b-2.gitbook.io/cs61b-textbook-2025/10.-inheritance-ii-extends-casting-higher-order-functions/10.4-higher-order-functions-in-java.md).

# 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.

```python
class Dog:
   def __init__(self, name, size):
       self.name = name
       self.size = size
  
   def __gt__(self, other):
       return self.size > other.size
```

```java
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.

```python
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)
```

```java
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:

```java
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.
