This is the lecture note of CS61B - Lecture 10.
⛱️ In this lecture, we will talk about Polymorphism
of Java, and continue discussing HoFs
deeply.
But before starting today's lecture, firstly, we will review concepts of the previous lecture with a puzzle.
Subtype Polymorphism
In the rest of this lecture, we will think about how to code the second approach in Java.
DIY Comparison
Suppose we want to write a function max()
that returns the max of any array, regardless of type.
1 | public static Object max(Object[] items) { |
To fix the error above, one approach is to write a max method in Dog class:
1 | public static Dog maxDog(Dog[] dogs) { |
But this is a bad way. What if we want to compare apples instead of dogs? Or cats, horses ...... 🤢
So we need another way !
We have already known that objects cannot be compared to other objects with >
, <
, ==
etc. In this case, inheritance/HoFs can help us.
Solution:
Create an interface that guarantees a comparison method:
1 | public interface OurComparable { |
Our dog class should implement the defined interface:
1 | public class Dog implements OurComparable { |
Define the function:
1 | public class Maximizer { |
1 | public class HoFDemo { |
Now, try to answer 2 quizzes. Hope you can finish them correctly.
Answer: quiz 1: B quiz 2: A
built-in Comparable Interface
Although the built OurComparable
works, it has some flaws. In the real world, we use a built-in interface named Comparable
.
1 | /** |
Rewrite the previous problem:
1 | public class Dog implements Comparable<Dog> { |
Comparators
We do not always want to compare objects in the same way every time, that is where Comparator
comes in.
Sometimes, maybe you actually want to sort them in a different way, like sorting them alphabetically.
1 | import java.util.Comparator; |
1 | import java.util.Comparator; |
The only difference between Comparable and Comparator is that Comparable
says "I wanna compare myself to other object", while Comparator
compares two other objects.