> For the complete documentation index, see [llms.txt](https://cs61b-2.gitbook.io/cs61b-textbook/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/11.-inheritance-iii-subtype-polymorphism-comparators-comparable/11.6-exercises.md).

# 11.6 Exercises

## Exercises

1. Which of the following are examples of subtype polymorphism?
   * [ ] Having a `sqrt(int)` and `sqrt(double)` method in the same class.
   * [ ] Having a `Dog` override the `makeSound` method that it inherits from `Animal`.
   * [ ] Creating a class that implements the built-in `Comparable` interface.
2. How would you compare two strings alphabetically in Java?
3. Suppose we correctly define a `Comparator` class called `SixComparator` for integers that compares them based on the number of `6`s they contain. What will the code `(new SixComparator()).compare(12345678, 45666678)` return?&#x20;
4. What is the main difference between the `Comparable` and `Comparator` interfaces?

## Solutions

<details>

<summary>Problem 1</summary>

**Having a `Dog` override the `makeSound` method that it inherits from `Animal`.**

Overriding `makeSound` allows us to have different implementations of the same method via subtypes.

**Creating a class that implements the built-in `Comparable` interface.**

Implementing the Comparable interface involves overriding Comparables’ methods, allowing for differing behavior of the same method across types.

</details>

<details>

<summary>Problem 2</summary>

`s1.compareTo(s2)`

</details>

<details>

<summary>Problem 3</summary>

It will return some negative number, since `12345678` has less `6`'s than `45666678`. Note that there is no guarantee of what the negative number's value is, only that it is less than 0.

</details>

<details>

<summary>Problem 4</summary>

An object that implements `Comparable` can compare another object to itself, whereas a Comparator compares two objects other than itself.&#x20;

A good way to remember this is that a `Comparable` has an inherent property of being *able* *to be compared*, while a `Comparator` is an external source of truth.

</details>
