Kotlin
Java

References and Polymorphism
Kotlin

Created By: Geoffrey Challen
/ Updated: 2021-09-30

Today's lesson combines what we've learned previously about polymorphism with what we now know about references. We'll examine how the type of a reference variable—not the type of what it refers to—determines what methods and field we can access using dot notation. We'll also use this opportunity to reinforce our developing view of references.

Reference v. Instance Type

When we introduced polymorphism and "is a" relationships, we introduced how the type of a variable and the type of the object stored in it could differ:

Now, using our more precise terminology, we can be more clear about exactly what is going on here:

Walk through an example showing the relationship between the reference variable type and the instance type. Show how the reference variable type determines what methods can be called.

Dot Notation

One additional piece of Kotlin syntax that should now become more clear is dot notation. We've been using it to access object fields and methods:

Now we know what is happening! The . causes Kotlin to follow the reference variable to the object it refers to: in this case it follows s to the String we created on the line above. If we create two references that lead to the same place, it will follow either:

More Reference Examples

With a bit more information under our belt, let's go over a few more important examples of places where references are used.

Pass by Reference

When a method is called in Kotlin, what is passed to the method is a reference, not a copy of the object. This allows the method to modify the object. Let's look at how this works!

Describe what happens as the code above runs.

And now, using a diagram to make the relationships clear visually:

Use a diagram to describe how call by reference works.

Arrays Store References

Kotlin arrays that store objects actually store object references. This has some important implications. Let's look at an example:

Go through an example making shallow and deep copies of an array of objects.

Generality v. Capability

Some of you might be wondering: why would I ever write a method that accepts Any? It seems like you lose so much information about the object by doing that!

While that is true, the tradeoff is with generality. Let's try and make that clear through an analogy:

Share an analogy that illustrates the difference between generality and capability.

Show how to complete the homework problem above. Feel free to cover multiple approaches!

Solution Walkthrough

Show how to complete the homework problem above. Feel free to cover multiple approaches!

Solution Walkthrough