Kotlin
Java

Implementing Interfaces
Java

Created By: Geoffrey Challen
/ Updated: 2021-10-05

Welcome back! Next we continue our journey with interfaces. In the last lesson we examined how to use interfaces. Now we'll look at how to provide them in our own classes, and the kind of amazing things that this can unleash. Let's go!

Implementing Interfaces

Last time we focused on using interfaces. In this lesson we'll discuss implementing them ourselves. Along the way we'll also discuss more about exactly how interfaces are so powerful.

Interfaces as Contract

As we begin to focus on using interfaces, it makes sense to think about an interface as a contract. When you implement an interface in one of your classes, you agree not only to provide certain methods, but also that these methods will do certain things!

Let's return to our favorite Java interface—Comparable—for an example of how to read an interface like a contract.

Go through the Comparable documentation and discuss how it serves as a contract between the implementer and the user.

Now, let's put what we've learned to use by designing a new class and making it Comparable!

Write a new class and make it comparable. Pick something that has a natural ordering.

Interfaces as Abstraction Barrier

Another important way to think about interfaces is as something called an abstraction barrier. An abstraction barrier separates two parts of a program or system in ways that allow them to develop independently. Again, let's return to Comparable to discuss exactly how that works!

Go through the Comparable documentation and discuss how it serves as an abstraction barries between the implementer and the user. Show some of the code out in the world that is ready to work on Comparable objects, like the one we just created!

Take the class that we just wrote using Comparable and show how it can be sorted, searched, etc.

Using v. Implementing

This is a distinction that can be tricky for people. So let's go through an example together and discuss the differences.

Discuss using v. implementing. Using: writing a method that takes an interface type. Implementing: actually adding implements to a class that we control.

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