# 11.1 A Review of Dynamic Method Selection

In previous lectures we have gone over classes extending other classes, and to make sense of this we considered whether the sub class has an "is-a relationship" with the superclass. For example, if we had the two classes:

* Dog: Implements bark() method
* ShowDog: Extends Dog, overrides bark method

This would be a valid extension as a ShowDog is-a Dog and a Dog is-an Object. These relationships satisfy the condition of a subclass being-an instance of the super class. &#x20;

![](/files/QuXyqZHsRGG1AfrqXyeJ)

## With this in Mind, what are the Rules to Decide if the Code Would Run or Run into Errors?

This is a particularly tricky problem to solve but the rules to look out for include:

* Compliers will allow Memory Boxes to hold any subtype of itself
  * For example, compliers will allow the Dog memory box to hold a ShowDog object as a ShowDog is a subtype of the Dog Class
* Compliers will allow calls based on Static type.
  * For example, if a variable were declared as a Dog it's static type would be a Dog and the complier would allowed it to call bark()
* **Overridden non-static methods are selected at run time based on dynamic type.**
  * **Everything else is based on static types,** inculding overloaded methods.

## Static Type vs. Dynamic Type

Every variable in Java has a “compile-time type”, a.k.a. “static type”.

* This is the type specified at declaration. Never changes!

\
Variables also have a “run-time type”, a.k.a. “dynamic type”.

* This is the type specified at instantiation (e.g. when using new).
* Equal to the type of the object being pointed at.

## Accompanying Lecture

{% embed url="<https://www.youtube.com/watch?ab_channel=JoshHug&v=cUL1LWVv984>" %}


---

# 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.1-a-review-of-dynamic-method-selection.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.
