Use Kotlin Classes

May 22 2024 · Kotlin 1.9.24, Android 14, Kotlin Playground

Lesson 05: Override Methods

Demo

Episode complete

Play next episode

Next
Transcript

In this demo, you’ll see what it takes to access your superclass’s full power.

Within your subclass methods, you can call the superclass method with the same name using super.methodName(). This allows you to reuse the superclass implementation and potentially extend it with your own logic.

There are several benefits to calling the superclass method implementation.

Reusing Existing Functionality

You can leverage the behavior defined in the superclass method while potentially adding or modifying it in your subclass. This means that by using methods from the parent class, you prevent writing the same code again and use features already built in the parent class.

Maintaining Correct Behavior

The superclass method might perform essential setup or initialization logic. Calling it guarantees that this critical code runs before your subclass’s specific implementation, which helps maintain the expected behavior established in the superclass hierarchy.

Extending Functionality

Calling super.methodName() helps you chain behaviors. You can execute the superclass logic and then add your own operations on top of it, which promotes a modular and well-structured codebase.

Example

Imagine a Vehicle class with a startEngine() method that performs basic engine checks. A subclass, ElectricCar, might override this method to include an additional check for sufficient battery level. Here’s how you could implement it:

open class Vehicle {
  open fun startEngine() {
    // Perform generic engine checks
    println("Performing generic engine checks")
  }
}

class ElectricCar(val batteryLevel: Double) : Vehicle() {
  override fun startEngine() {
    super.startEngine() // Call superclass checks first
    if (batteryLevel > 0.2) {
      println("Electric car: Battery level sufficient, ready to start!")
    } else {
      println("Electric car: Low battery, cannot start!")
    }
  }
}

fun main() {
  val tesla = ElectricCar(0.1)
  tesla.startEngine()
}

In this example, ElectricCar calls super.startEngine() to reuse the generic checks. Then, it adds its specific battery level check before deciding to start the engine.

Note: You can only call a superclass constructor from the subclass constructor. You can call superclass methods from anywhere within the subclass methods. Using super effectively promotes code reusability and reduces redundancy.

See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion