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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://cs61b-2.gitbook.io/cs61b-textbook/11.-inheritance-iii-subtype-polymorphism-comparators-comparable/11.6-exercises.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
