0
0
Kotlinprogramming~5 mins

Overriding methods with override in Kotlin

Choose your learning style9 modes available
Introduction

Overriding lets you change how a method works in a child class. It helps you customize behavior while keeping the same method name.

When you want a child class to do something different from its parent class for the same action.
When you need to add extra steps before or after the original method runs.
When you want to fix or improve how a method works in a subclass.
When you want to provide specific behavior for different types of objects in a class hierarchy.
Syntax
Kotlin
open class Parent {
    open fun greet() {
        println("Hello from Parent")
    }
}

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

The open keyword allows a method to be overridden.

The override keyword tells Kotlin you are changing the parent's method.

Examples
Here, Dog changes the sound method to print "Bark" instead of "Some sound".
Kotlin
open class Animal {
    open fun sound() {
        println("Some sound")
    }
}

class Dog : Animal() {
    override fun sound() {
        println("Bark")
    }
}
Car overrides start to give a specific message.
Kotlin
open class Vehicle {
    open fun start() {
        println("Vehicle starting")
    }
}

class Car : Vehicle() {
    override fun start() {
        println("Car starting")
    }
}
Sample Program

This program shows how Student changes the introduce method from Person. When run, it prints different greetings.

Kotlin
open class Person {
    open fun introduce() {
        println("Hi, I am a person.")
    }
}

class Student : Person() {
    override fun introduce() {
        println("Hi, I am a student.")
    }
}

fun main() {
    val person = Person()
    val student = Student()
    person.introduce()
    student.introduce()
}
OutputSuccess
Important Notes

You must mark the parent method with open to allow overriding.

Use override in the child method to avoid mistakes and make your code clear.

If you forget override, Kotlin will give an error.

Summary

Use open on parent methods to allow overriding.

Use override in child classes to change method behavior.

Overriding helps customize how objects behave while keeping the same method names.