0
0
KotlinHow-ToBeginner · 3 min read

How to Override Method in Kotlin: Syntax and Examples

In Kotlin, to override a method, the base class method must be marked with open, and the subclass method must use the override keyword. This tells Kotlin you are providing a new implementation for the inherited method.
📐

Syntax

To override a method in Kotlin, the method in the parent class must be marked with open. The child class then uses the override keyword before the method name to provide a new implementation.

  • open fun methodName(): Declares a method that can be overridden.
  • override fun methodName(): Overrides the parent method.
kotlin
open class Parent {
    open fun greet() {
        println("Hello from Parent")
    }
}

class Child : Parent() {
    override fun greet() {
        println("Hello from Child")
    }
}
💻

Example

This example shows a parent class with an open method and a child class that overrides it. When calling the method on the child, the overridden version runs.

kotlin
open class Animal {
    open fun sound() {
        println("Some generic animal sound")
    }
}

class Dog : Animal() {
    override fun sound() {
        println("Bark")
    }
}

fun main() {
    val myDog = Dog()
    myDog.sound()  // Calls overridden method
}
Output
Bark
⚠️

Common Pitfalls

Common mistakes include forgetting to mark the parent method as open, which causes a compile error when trying to override. Also, missing the override keyword in the child method will cause an error because Kotlin requires explicit overriding.

Another pitfall is trying to override a final method, which is not allowed.

kotlin
open class Vehicle {
    fun drive() {  // Not open, cannot override
        println("Driving")
    }
}

class Car : Vehicle() {
    // This will cause a compile error:
    // override fun drive() {
    //     println("Car driving")
    // }
}

// Correct way:
open class VehicleCorrect {
    open fun drive() {
        println("Driving")
    }
}

class CarCorrect : VehicleCorrect() {
    override fun drive() {
        println("Car driving")
    }
}
📊

Quick Reference

KeywordPurpose
openMarks a method as overridable in the parent class
overrideMarks a method as overriding a parent method in the child class
finalPrevents a method from being overridden (default if not open)

Key Takeaways

Mark parent class methods with open to allow overriding.
Use override keyword in child class to replace the parent method.
Kotlin requires explicit open and override keywords for method overriding.
You cannot override methods that are not open or are final.
Forgetting open or override keywords causes compile-time errors.