Kotlinlearncs.online LogoJava

Implementing Interfaces

import kotlin.random.Random
import java.util.Arrays
data class Counter(private var value: Int) : Comparable<Counter> {
fun up() {
value++
}
fun down() {
value--
}
override fun compareTo(other: Counter): Int {
return value - other.value
}
}
val counters = Array<Counter>(8) { Counter(Random.nextInt(32)) }
println(counters.contentToString())
Arrays.sort(counters)
println(counters.contentToString())

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
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
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. Keep in mind that we can use this interface in Kotlin even though it is provided by Java!

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

// Implementing Comparable

Interfaces as Abstraction Barrier
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!

// The Wide World of Comparable

Practice: Last Odd Interface

Created By: learncs.online Staff
/ Version: 2020.10.0

Create a public class LastOdd that implements the following interface:

Using v. Implementing
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.

// Using v. Implementing

Homework: Running Total Interface

Created By: learncs.online Staff
/ Version: 2021.10.0

Create a public class RunningTotal that implements the following interface:

More Practice

Need more practice? Head over to the practice page.