Skip to Content
Course content

20: Inheritance and Interfaces

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I want to show you a snippet of code I reviewed recently from a junior dev who was building a payment processing module. They were coming from Java, and they hit a wall that almost every Java developer hits when they first move to Kotlin.

class Payment(val amount: Double) {
    fun process() {
        println("Processing generic payment of $$amount")
    }
}

class CreditCardPayment(amount: Double, val cardNumber: String) : Payment(amount) {
    override fun process() {
        println("Processing credit card $cardNumber for $$amount")
    }
}

If you try to compile this, the compiler will scream at you with two different errors: first, that Payment is "final" and cannot be inherited from, and second, that process() cannot be overridden. In Java, classes are open by default. In Kotlin, it's the exact opposite.

Unlocking Classes with the Open Keyword

Kotlin assumes you don't want your classes to be inherited unless you explicitly say so. This is a design choice to prevent the "fragile base class" problem, where changing a parent class accidentally breaks a dozen children you didn't know existed. To fix the code above, we have to use the open modifier.

open class Payment(val amount: Double) {
    open fun process() {
        println("Processing generic payment of $$amount")
    }
}

class CreditCardPayment(amount: Double, val cardNumber: String) : Payment(amount) {
    override fun process() {
        println("Processing credit card $cardNumber for $$amount")
    }
}

Now it works. Note that I had to mark both the class and the specific function as open. If you open the class but forget to open the function, you still can't override that method. I personally find this verbosity a bit annoying at first, but once you're working on a large codebase, I promise you'll appreciate knowing exactly which parts of the hierarchy are meant to be extended.

Using Interfaces for Shared Capabilities

Inheritance is great for "is-a" relationships (a CreditCardPayment is a Payment). But what happens when you have a capability that spans across unrelated classes? For example, some payments are Refundable, but others—like a gift card or a crypto transaction—might not be. You can't put refund() in the Payment base class because then you'd be forcing every single payment type to implement a refund method, even if it's impossible for that type.

This is where interfaces come in. An interface defines a contract: "I don't care who you are, as long as you can do this."

interface Refundable {
    fun refund()
}

class CreditCardPayment(amount: Double, val cardNumber: String) : Payment(amount), Refundable {
    override fun process() {
        println("Processing credit card $cardNumber for $$amount")
    }

    override fun refund() {
        println("Refunding payment to card $cardNumber")
    }
}

class CryptoPayment(amount: Double, val walletAddress: String) : Payment(amount) {
    override fun process() {
        println("Processing crypto payment from $walletAddress")
    }
    // No refund() here, because CryptoPayment doesn't implement Refundable
}

Deciding Between Abstract Classes and Interfaces

You'll often wonder: "If an interface can have default implementations, why do I need abstract classes?" Here is my rule of thumb: use an abstract class for identity (what the object is) and an interface for ability (what the object can do).

An abstract class is perfect when you want to share state (like that amount property in our Payment class). Interfaces cannot hold state; they can't have backing fields. If you find yourself needing to store a variable that all subclasses should use, you need a class, not an interface.

If you make a class abstract, you're telling Kotlin: "This class is incomplete. You can't instantiate it directly; you can only use it as a blueprint for other classes." This is even more powerful than open because it allows you to define abstract methods that must be implemented by any child class.

abstract class Payment(val amount: Double) {
    abstract fun process() // No body here! Subclasses MUST implement this.
}



📋 Practical Task

Building a Smart Home Device Hierarchy

You are designing a system to control smart home devices. Your task is to implement a hierarchy that separates the "identity" of the device from its "capabilities."

  • Create an abstract class called SmartDevice. It should have a property deviceName: String and an abstract function turnOn().
  • Create an interface called Dimmable. It should have a function setBrightness(level: Int).
  • Implement a class SmartLight that inherits from SmartDevice and implements Dimmable.
  • Implement a class SmartPlug that inherits from SmartDevice but does not implement Dimmable.
  • In your main function, create a list of SmartDevice objects containing both a light and a plug. Iterate through them and call turnOn().
  • Finally, write a check to see if a device is Dimmable using the is keyword, and if so, call setBrightness(50).
Rating
0 0

There are no comments for now.

to be the first to leave a comment.